Professional Documents
Culture Documents
What is C?
C is a compiler based programming language supports both high level and low level statements to
interact directly with the hardware.
Development of C Language
The C programming language evolved from a succession of programming languages developed at Bell
Laboratories in early 1970s. It was not until the late 1970s that this programming language began to
gain widespread popularity and support. This was because until that time C compilers were not readily
available for commercial use outside of Bell Laboratories.
The C language was the outcome of Dennis Ritchies work on a project in Bell Laboratories, to invent a
suitable high level language for writing an Operating System which manages the input and output
devices of a computer, allocates its storage and schedules the running of other programs.
UNIX operating system is written in the C language. Hence the Unix Operating system has C as its
standard programming language. In fact over 90% of the operating system itself is written in the C
language. So originally C language was designed and implemented on the Unix Operating System.
C stands somewhere between the high-level languages meant for carrying on special activities and the
low level languages such as assembly language of a machine because of some features like System
Independence, Limited Data Type, High Flexibility, it is considered as a powerful language C has
also become popular because of its portability across systems.
History of C
Year Language Developed by Remarks
1960 ALGOL International Committee Too general, Too abstract
1963 CPL Cambridge University Hard to learn, Difficult to implement
Could deal with only specific
1967 BCPL Martin Richards
problems
Could deal with only specific
1970 B Ken Thompson AT & T Bell Labs
problems
Features of C
- Simple, versatile, general purpose language
- Programs are fast and efficient
- Has got rich set of operators
- more general and has no restrictions
- can easily manipulates with bits, bytes and addresses
- Varieties of data types are available
- separate compilation of functions is possible and such functions can be called by any C program
- block-structured language
- Can be applied in System programming areas like operating systems, compilers & Interpreters,
Assemblers etc.,
1. Constants
2. Variables
3. Operators
4. Statements
So, before writing serious programming we must be clear with all the above components of programs.
According to above example every program is a set of statements, and statement is an instruction to
the computer, which is a collection of constants, variables, operators and statements.
Constants
A constant is a fixed value, which never altered during the execution of a program.
Constants can be divided into two major categories:
1. Primary Constants
2. Secondary Constants
Data Types
The kind of data that the used variables can hold in a programming language is known as the data
type.
Basic data types are as follows:
1. Numeric Data Type
2. Non-Numeric Data Type
3. Integer Data Type
2. Non-Numeric Data Type : Totally deals with characters. Any character or group of characters
enclosed within quotes will be considered as non-numeric or character data type.
3. Integer Data Type : Deals with integers or whole numbers. All arithmetic operations can be
achieved through this data type and the results are again integers.
4. Real Data Type : deals with real numbers or the numeric data, which includes fractions. All
arithmetic operations can be achieved through this data type and the results can be real data type.
5. Logical or Boolean Data Type : can hold only either of the two values TRUE or FALSE at a time. In
computer, a 1 (one) is stored for TRUE and a 0 (zero) is stored for FALSE.
6. Enumerated Data Type : Includes the unstructured data grouped together to lead to a new type.
This data type is not standard and us usually defined by user.
Ex.
Week_days = { sun, mon, tue, wed, thu, fri, sat };
Directions = {North, East, West, South };
C - Basic Syntax
Basic Structure of C Programs
C programs are essentially constructed in the following manner, as a number of well defined
sections.
/* HEADER SECTION */
/* Contains name, author, revision number*/
/* INCLUDE SECTION */
/* contains #include statements */
/* FUNCTIONS SECTION */
/* user defined functions */
int main()
{
}
Adhering to a well defined structured layout will make your programs
easy to read
easy to modify
consistent in format
self documenting
Structure of a C program
<Statement block>
#include <stdio.h>
should be at the beginning of the source file, because the definition for printf() is found in the
file stdio.h All header files have the extension .h and generally reside in the /include subdirectory.
#include <stdio.h>
#include "mydecls.h"
I/O Statements
Print
This statement displays the given literal / prompt / identifiers on the screen with the given format.
Syntax:
printf(<"prompt/literal/format id/esc char. ">, id1,id2, .....);
E.g.:
printf("Hello");
printf("Student number : %d", sno);
printf("Student name : %s", name);
printf("3Subjects Marks : %d, %d, %d", m1, m2, m3);
/* 03_esc.c */
#include <stdio.h>
int main()
{
printf("\nHello");
return 0;
}
3. Program to display address of a person
- Multiple statements in main
/* 04_multi.c */
#include <stdio.h>
int main()
{
printf("\nName of the Person");
printf("\nStreet, Apartment//House No. ");
printf("\nzip, City");
printf("\nCountry");
return 0;
}
Scanf
Using this statement we can accept and values to variables during the execution of the program.
Syntax:
scanf(<format id/esc char">, id1,id2, .....);
Eg.
scanf("%d", &sno);
scanf("%s", name);
scanf("%d%d%d", &m1, &m2, &m3);
/* 07_scanf.c */
#include <stdio.h>
int main()
{
int a , b, c; scanf("%d", &a);
scanf("%d", &b);
c = a + b;
/* 08_sum.c */
#include <stdio.h>
int main()
{
int a , b, c; printf("Enter A value "); scanf("%d", &a);
printf("Enter B value "); scanf("%d", &b);
c = a + b;
printf("\nSum is %d", c);
return 0;
}
8. Program to find the result of ( a+ b )2
- Similar to sum of two values program but the formulae is different
/* 09_formula.c */
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter A value "); scanf("%d", &a);
printf("Enter B value "); scanf("%d", &b);
c = a * a + b * b + 2 * a * b;
/* 10_emp.c */
#include <stdio.h>
int main()
{
int eno;
/* 11_stud.c */
#include <stdio.h>
int main()
{
int sno, sub1, sub2, sub3, total;
char name[10];
float avg;
getch
It accepts a character from console.
Syntax:
char = getch().
E.g.:
ch = getch();
option = getch();
You have seen the basic structure of a C program, so it will be easy to understand other basic building
blocks of the C programming language.
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a
string literal, or a symbol. For example, the following C statement consists of five tokens
print
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
Comments
Comments are like helping text in your C program and they are ignored by the compiler. They start
with /* and terminate with the characters */ as shown below
/* my first program in C */
You cannot have comments within comments and they do not occur within a string or character
literals.
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An
identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters,
underscores, and digits (0 to 9).
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants
or variables or any other identifier names.
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler
totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify
where one element in a statement, such as int, ends and the next element begins. Therefore, in the
following statement
int age;
there must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement
no whitespace characters are necessary between fruit and =, or between = and apples, although you
are free to include some if you wish to increase readability.
An example of an integer value is 32. An example of declaring an integer variable called sum is,
int sum;
sum = 20;
FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword
used to define float variables is,
float
An example of a float value is 34.12. An example of declaring a float variable called money is,
float money;
money = 0.12;
DOUBLE
These are exponetional numbers, both positive and negative. The keyword used to define
double variables is,
double
An example of a double value is 3.0E2. An example of declaring a double variable called big is,
double big;
big = 312E+7;
CHARACTER
These are single characters. The keyword used to define character variables is,
char
main()
{
int sum;
float money;
char letter;
double pi;
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and how the
bit pattern stored is interpreted.
2 They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.
Derived types
4 They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and
(e) Function types.
The array types and structure types are referred collectively as the aggregate types. The type of a
function specifies the type of the function's return value. We will see the basic types in the following
section, where as other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and value
ranges
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
-32,768 to 32,767 or -2,147,483,648 to
Int 2 or 4 bytes
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platorm, you can use the sizeof operator.
The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an
example to get the size of int type on any machine
#include <stdio.h>
#include <limits.h>
When you compile and execute the above program, it produces the following result on Linux
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and value
ranges and their precision
Type Storage size Value range Precision
float 4 byte 1. 2E-38 to 3.4E+38 6 decimal places
double 8 byte 2. 3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3. 4E-4932 to 1.1E+4932 19 decimal places
The header file float.h defines macros that allow you to use these values and other details about the
binary representation of real numbers in your programs. The following example prints the storage
space taken by a float type and its range values
#include <stdio.h>
#include <float.h>
int main() {
print("Storage size for float : %d \n", sizeof(float));
print("Minimum float positive value: %E\n", FLT_MIN );
print("Maximum float positive value: %E\n", FLT_MAX );
print("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and execute the above program, it produces the following result on Linux
The void type specifies that no value is available. It is used in three kinds of situations
S.N.0 Types & Description
Function returns as void
There are various functions in C which do not return any value or you can say they return
1 void. A function with no return value has the return type as void. For example, void exit
(int status);
Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example,
3 a memory allocation function void *malloc( size_t size ); returns a pointer to void which
can be casted to any data type.
C - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-
sensitive. Based on the basic types explained in the previous chapter, there will be the following basic
variable types
Type Description
char Typically a single octet(one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as
follows
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by commas.
Some valid declarations are shown here
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create
variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given
type and name so that the compiler can proceed for further compilation without requiring the
complete detail about the variable. A variable definition has its meaning at the time of compilation
only, the compiler needs actual variable definition at the time of linking the program.
Example
Try the following example, where variables have been declared at the top, but they have been defined
and initialized inside the main function
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
print("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
When the above code is compiled and executed, it produces the following result
value of c : 30
value of f : 23.333334
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
count = 32;
letter = 'A';
#include <stdio.h>
main()
{
int count;
char letter;
It can be seen from the sample output that the values which each of the variables take on at
declaration time are no-zero. In C, this is common, and programmers must ensure that variables are
assigned values before using them.
If the program was run again, the output could well have different values for each of the variables. We
can never assume that variables declare in the manner above will take on a specific value.
Some compilers may issue warnings related to the use of variables, and Turbo C from Borland issues
the following warning,
RADIX CHANGING
Data numbers may be expressed in any base by simply altering the modifier, e.g., decimal, octal, or
hexadecimal. This is achieved by the letter which follows the % sign related to the printf argument.
#include <stdio.h>
The following program illustrates how the different data types are declared and displayed,
#include <stdio.h>
main()
{
int sum = 100;
char letter = 'Z';
float set1 = 23.567;
double num2 = 11e+23;
In this case, the use of %.2f limits the output to two decimal places, and the output now looks like
Sample program output
Integer variable is 100
Character variable is Z
Float variable is 23.56
Double variable is 11.000000e23
int main()
{
int m = 22, n = 44;
// m, n are local variables of main function
/*m and n variables are having scope
within this main function only.
These are not visible to test funtion.*/
/* If you try to access a and b in this function,
you will get 'a' undeclared and 'b' undeclared error */
print("\nvalues : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope
within this test function only.
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
int main()
{
print("All variables are accessed from main function");
print("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
void test()
{
print("\n\nAll variables are accessed from" \
" test function");
print("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
OUTPUT:
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
3. ENVIRONMENT VARIABLES IN C:
Environment variable is a variable that will be available for all C applications and C programs.
We can access these variables from anywhere in a C program without declaring and initializing in an
application or C program.
The inbuilt functions which are used to access, modify and set these environment variables are called
environment functions.
There are 3 functions which are used to access, modify and assign an environment variable in C. They
are,
1. setenv()
2. getenv()
3. putenv()
#include <stdio.h>
#include <stdlib.h>
OUTPUT:
/usr/bin/test/
EXAMPLE PROGRAM FOR SETENV() FUNCTION IN C:
This function sets the value for environment variable. Let us assume that environment variable FILE
is to be assigned /usr/bin/example.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("FILE", "/usr/bin/example.c",50);
print("File = %s\n", getenv("FILE"));
return 0;
}
OUTPUT:
File = /usr/bin/example.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("DIR", "/usr/bin/example/",50);
print("Directory name before modifying = " \
"%s\n", getenv("DIR"));
OUTPUT:
main()
{
int i;
while( i < 3 ) {
demo();
i++;
}
}
Static variables are created and initialized once, on the first call to the function. Subsequent calls to
the function do not recreate or re-initialize the static variable. When the function terminates, the
variable still exists on the _DATA segment, but cannot be accessed by outside functions.
Automatic variables are the opposite. They are created and re-initialized on each entry to the function.
They disappear (are de-allocated) when the function terminates. They are created on the _STACK
segment.
MORE ABOUT VARIABLES
Variables must begin with a character or underscore, and may be followed by any combination of
characters, underscores, or the digits 0 - 9. The following is a list of valid variable names,
summary
exit_flag
i
Jerry7
Number_of_moves
_valid_flag
You should ensure that you use meaningful names for your variables. The reasons for this are,
meaningful names for variables are self documenting (see what they do at a glance)
they are easier to understand
there is no correlation with the amount of space used in the .EXE file
CLASS EXERCISE C3
Why are the variables in the following list invalid,
value$sum
exit flag
3lotsofmoney
char
C - Scope Rules
A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable it cannot be accessed. There are three places where variables can be
declared in C programming language
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all the
variables a, b, and c are local to main() function.
#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
print ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but the value of local variable inside a
function will take preference. Here is an example
When the above code is compiled and executed, it produces the following result
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence over
global variables. Following is an example
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
print ("value of a in main() = %d\n", a);
c = sum( a, b);
print ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
When the above code is compiled and executed, it produces the following result
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global
variables are initialized automatically by the system when you define them as follows
}
}
The adjective lexical is used synonymously with static, because both pertain to the lexicon (the
words, the source) of the program.
Dynamically, one examines what happens while executing the program (at runtime). Given
the following code, f and g have a dynamic relationship, because f invokes g.
function g() {
}
function f() {
g();
}
A statement
var x = ...;
establishes a binding for the variable x that maps the variable name to a value. In the following, the
terms variable and binding are often used interchangeably. This is less precise, but makes
explanations shorter. Bindings are characterized by:
Scope (a spatial property): Where can the binding be accessed?
Extent (a temporal property): How long does the binding exist?
There are several variations of implementing scope and extent in a programming language.
Scope: The direct scope of a variable is the syntactic construct in which a binding has been created.
What constructs form scopes depends on the programming language: any kind of block in most
languages, only functions in JavaScript. One has two options when it comes to determining where else
a variable is accessible, in addition to the direct scope:
Static (lexical) scoping: A variable is accessible from the direct scope and all scopes lexically
nested in it. In the following example, x is visible in its direct scope, function f, but also in the
nested scope, function g.
function f() {
var x;
function g(y) {
return x + y;
}
}
Most modern programming languages use static scoping. Some, such as Common Lisp, additionally
support dynamic scoping (for dynamically encapsulated global variables). Two effects influence
scoping:
Scopes can be nested. The direct scope can be seen as nesting all other scopes where a
variable is accessible. In that case, the nested scopes are called inner scopes, the direct scope is
called outer scope. In static scoping, nesting happens by nesting syntactic constructs. In
dynamic scoping, nesting happens by recursively invoking functions.
Variables can be shadowed. If an inner scope declares a variable with the same name as a
variable in an outer scope, the outer variable is shadowed by the inner one: it cannot be
accessed in the inner scope (or scopes nested in it), because mentions of it refer to the inner
binding. In the following example, the declaration in g shadows the declaration in f. Thus, x has
the value "bar" in g and in h.
function f() {
var x = "foo";
function g() {
var x = "bar";
function h() {
}
}
}
Note that there exist many different definitions of extent in the literature. We have covered just one
of them [1].
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after their
definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals
85 /* decimal */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both; and
while representing exponential form, you must include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash for
example, newline (\n) or tab (\t).
Here, you have a list of such escape sequence codes
#include <stdio.h>
int main() {
print("Hello\tWorld\n\n");
return 0;
}
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using white
spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
Defining Constants
There are two simple ways in C to define constants
Using #define preprocessor.
Using const keyword.
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
When the above code is compiled and executed, it produces the following result
value of area : 50
You can use const prefix to declare constants with a specific type as follows
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
print("value of area : %d", area);
print("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.
C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used
within functions, i.e., local variables.
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also
be noted that defining 'register' does not mean that the variable will be stored in a register. It means
that it MIGHT be stored in a register depending on hardware and implementation restrictions.
In C programming, when static is used on a global variable, it causes only one copy of that member to
be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
print("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions as explained below.
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
#include <stdio.h>
extern int count;
void write_extern(void) {
print("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in the first
file, main.c. Now, compile these two files as follows
count is 5
C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators
Arithmetic Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then
Show Examples
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then
Show Examples
Operator Description Example
Called Logical AND operator. If both the operands are non-zero, then the (A && B) is
&&
condition becomes true. false.
Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is
||
the condition becomes true. true.
Called Logical NOT Operator. It is used to reverse the logical state of its
!(A && B) is
! operand. If a condition is true, then Logical NOT operator will make it
true.
false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows
A = 0011 1100
B = 0000 1101
-----------------
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then
Show Examples
Operator Description Example
Binary AND Operator copies a bit to the result if it exists
& (A & B) = 12, i.e., 0000 1100
in both operands.
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, i.e., 0011 1101
operand.
Binary XOR Operator copies the bit if it is set in one
^ (A ^ B) = 49, i.e., 0011 0001
operand but not both.
Binary Ones Complement Operator is unary and has the (~A ) = -61, i.e,. 1100 0011 in
~
effect of 'flipping' bits. 2's complement form.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the right A << 2 = 240 i.e., 1111 0000
operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the right A >> 2 = 15 i.e., 0000 1111
operand.
Assignment Operators
The following table lists the assignment operators supported by the C language
Show Examples
Operator Description Example
Simple assignment operator. Assigns values from right side C = A + B will assign the
=
operands to left side operand value of A + B to C
Add AND assignment operator. It adds the right operand to C += A is equivalent to C =
+=
the left operand and assign the result to the left operand. C+A
Subtract AND assignment operator. It subtracts the right
C -= A is equivalent to C =
-= operand from the left operand and assigns the result to the
C-A
left operand.
Multiply AND assignment operator. It multiplies the right
C *= A is equivalent to C =
*= operand with the left operand and assigns the result to the
C*A
left operand.
Divide AND assignment operator. It divides the left operand
C /= A is equivalent to C =
/= with the right operand and assigns the result to the left
C/A
operand.
%= Modulus AND assignment operator. It takes modulus using C %= A is equivalent to C =
Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Show Examples
Operator Description Example
Returns the size of a
sizeof() sizeof(a), where a is integer, will return 4.
variable.
Returns the address of a
& &a; returns the actual address of the variable.
variable.
* Pointer to a variable. *a;
?: Conditional Expression. If Condition is true ? then value X : otherwise value Y
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Category Operator Associativity
Postix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
FORMAT SPECIFIERS
In C programming we need lots of format specifier to work with various data types. Format
specifiers defines the type of data to be printed on standard output. Whether to print formatted
output or to take formatted input we need format specifiers. Format specifiers are also called as
format string.
Format specifiers are the operators used in print() function to print the data which is referred by an
object or a variable. when a value is stored in a particular variable, Then we cannot print the value
stored in the variable directly with out the using format specifiers. We can retrieve the data stored in
the variables and can print them on to the console screen by using these format specifiers in a print
function. Format specifiers start with a percentage(%) symbol and follows a special character to
identify the type of the data. There are basically six types of format specifiers are available in c they
are
%d
%f
%c
%s
%u
%ld
I will explain all these six format specifiers available in c clearly. Keep reading.........
The above example is used to print the value stored in the variable a. Here the variable a returns a
value to the print function and the returned value is printed using the %d format specifier. For
example if there is a integer data 10 in the variable a, then after returning the value, the print
function look like
print("%d",10);
Here
%f is the format specifier for an floating or fractional data
variable name is the name of the float variable
When ever we declare the print statement using above syntax, the float variable returns the value
stored in it. Then the returned fractional value is printed by using the float format specifier %f.
The above example is used to print the value stored in the variable a. Here the variable a returns a
value to the print function and the returned value is printed using the %f format specifier. For
example if there is a fractional data 5.5 in the variable a, then after returning the value, the print
Now the returned value 5.5 is printed by using the %f format specifier.
The above example is used to print the character stored in the variable a. Here the variable a returns a
character to the print function and the returned character is printed using the %c format specifier. For
example if there is a character 'S' in the variable a, then after returning the value, the print function
look like
print("%c",S);
Now the returned character 'S' is printed by using the %c format specifier.
The above example is used to print the string stored in the character array variable a. Here the
variable a returns a value to the print function and the returned value is printed using the %s format
specifier. For example if there is a string "codershunt" in the variable a, then after returning the string,
the print function look like
print("%s",codershunt);
Now the returned string "codershunt" is printed by using the %s format specifier.
Here
%u is the format specifier for representing the address of a variable
variable name is the name of the variable
When ever we declare the print statement using above syntax, Then the memory address of the
specified variable will be printed.
The above example is used to print the memory address of the variable a.
The above example is used to print the long integer value stored in the variable a. Here the variable a
returns a value to the print function and the returned long integer value is printed using the %ld
format specifier. For example if there is a long integer data 45232 in the variable a, then after
returning the value, the print function look like
print("%ld",45232);
Now the returned value 45232 is printed by using the %ld format specifier.
The print() function should follow a semi colon at the end. This indicates the compiler that It is the
end of the statement.
As C is a case sensitive language so you should not use capital letters while writing print() function.
how ever you can use capital letters in the body of the message which is to be printed.
Here is a complete list of all format specifiers used in C programming language.
C is the most widely used computer language, that keeps fluctuating at number one scale of
popularity along with Java programming language which is also equally popular and most widely used
among modern software programmers.
The C Standard Library is a set of C built-in functions, constants and header files like <stdio.h>,
<stdlib.h>, <math.h>, etc. This library will work as a reference manual for C programmers.
Prerequisites
A basic understanding of the C Programming language will help you in understanding the C built-in
functions covered in this library.
C Library - <assert.h>
The assert.h header file of the C Standard Library provides a macro called assert which can be used to
verify assumptions made by the program and print a diagnostic message if this assumption is false.
The defined macro assert refers to another macro NDEBUG which is not a part of <assert.h>. If
NDEBUG is defined as a macro name in the source file, at the point where <assert.h> is included,
the assert macro is defined as follows
Library Macros
C Library - <ctype.h>
The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.
All the functions accepts int as a parameter, whose value must be EOF or representable as an
unsigned char.
All the functions return non-zero (true) if the argument c satisfies the condition described, and
zero(false) if not.
Character Classes
S.NO Character Class & Description
Digits
1
This is a set of whole numbers { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.