C Program Execution Flow Explained
C Program Execution Flow Explained
The C program follows many steps in execution. To understand the flow of C program well, let us see
a simple program first.
File: simple.c
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
Execution Flow
Let's try to understand the flow of above program by the figure given below.
1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert
preprocessor directives into their respective values. The preprocessor generates an expanded source
code.
2) Expanded source code is sent to compiler which compiles the code and converts it into assembly
code.
3) The assembly code is sent to assembler which assembles the code and converts it into object code.
Now a [Link] file is generated.
1
4) The object code is sent to linker which links it to the library such as header files. Then it is
converted into executable code. A [Link] file is generated.
5) The executable code is sent to loader which loads it into memory and then it is executed. After
execution, output is sent to console.
printf() function
The printf() function is used for output. It prints the given statement to the console.
1. printf("format string",argument_list);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
Let's see a simple example of c language that gets input from the user and prints the cube of the given
number.
1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the given
value in number variable.
2
Variables in C
A variable is a name of memory location. It is used to store data. Its value can be changed and it can
be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
type variable_list;
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. Its size is given according to 32 bit architecture.
3
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a',
3.4, "c programming" etc.
1. const keyword
2. #define preprocessor
1) C const keyword
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }
Output:
If you try to change the the value of PI, it will render compile time error.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }
Output:
4
2) C #define preprocessor
C #define
The #define preprocessor directive is used to define constant or micro substitution. It can use
any basic data type.
Syntax:
1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }
Output:
3.140000
C if else Statement
The if statement in C language is used to perform operation on the basis of condition. By
using if-else statement, you can perform operation either condition is true or false.
If statement
If-else statement
If else-if ladder
Nested if
If Statement
The single if statement in C language is used to execute the code if condition is true. The
syntax of if statement is given below:
1. if(expression){
2. //code to be executed
3. }
5
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
enter a number:4
4 is even number
If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false.
The syntax of if-else statement is given below:
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
simple example of even and odd number using if-else statement in C language.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
The if else-if statement is used to execute one code from multiple conditions. The syntax of if
else-if statement is given below:
6
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:4
number is not equal to 10, 50 or 100
C Switch Statement
The switch statement in C language is used to execute the code from multiple conditions. It is
like if else-if ladder statement.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
7
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement
found in switch case, all the cases will be executed after matching the case value. It is known
as fall through state of C switch statement.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }
Output
enter a number:4
number is not equal to 10, 50 or 100
C Loops
8
The loops in C language are used to execute a block of code or a part of the program several
times.
Suppose that you have to print table of 2, then you need to write 10 lines of code.
Advantage of loops in C
1) It saves code.
Types of C Loops
1. do while
2. while
3. for
do-while loop in C
It iterates the code until condition is false. Here, condition is given after the code. So at least
once, code is executed whether condition is true or false.
1. do{
2. //code to be executed
3. }while(condition);
do while example
There is given the simple program of c language do while loop where we are printing the
table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
9
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
while loop in C
Like do while, it iterates the code until condition is false. Here, condition is given before the
code. So code may be executed 0 or more times.
1. while(condition){
2. //code to be executed
3. }
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
10
5
6
7
8
9
10
for loop in C
Like while, it iterates the code until condition is false. Here, initialization, condition and
increment/decrement is given before the code. So code may be executed 0 or more times.
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
C break statement
11
The break statement in C language is used to break the execution of loop (while, do while
and for) and switch case.
Syntax:
1. jump-statement;
2. break;
The jump statement in c break syntax can be while loop, do while loop, for loop or switch
case.
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. printf("%d \n",i);
7. if(i==5){//if value of i is equal to 5, it will break the loop
8. break;
9. }
10. }
11. return 0;
12. }
Output
1
2
3
4
5
As you can see on console output, loop from 1 to 10 is not printed after i==5.
C continue statement
The continue statement in C language is used to continue the execution of loop (while, do
while and for). It is used with if condition within the loop.
12
Syntax:
1. jump-statement;
2. continue;
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally
jump to other label. It transfers control to other parts of the program.
It is rarely used today because it makes program less readable and complex.
Syntax:
1. goto label;
13
goto example
1. #include <stdio.h>
2. int main() {
3. int age;
4. ineligible:
5. printf("You are not eligible to vote!\n");
6.
7. printf("Enter you age:\n");
8. scanf("%d", &age);
9. if(age<18)
10. goto ineligible;
11. else
12. printf("You are eligible to vote!\n");
13.
14. return 0;
15. }
Output:
Type Casting in C
Type casting allows us to convert one data type into other. In C language, we use cast
operator for type casting which is denoted by (type).
Syntax:
1. (type)value;
Note: It is always recommended to convert lower value to higher for avoiding data loss.
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
14
Type Casting example
1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }
Output:
f : 2.250000
functions in C
The function in C language is also known as procedure or subroutine in other programming
languages.
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions in C
1) Code Reusability
By creating functions in C, you can call it many times. So we don't need to write the same
code again and again.
2) Code optimization
Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several
times.
Types of Functions
15
1. Library Functions: are the functions which are declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces complexity of a big program and optimizes the
code.
Declaration of a function
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
1. void hello(){
2. printf("hello c");
3. }
If you want to return any value from the function, you need to use any data type such as int,
long, char etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
1. int get(){
2. return 10;
3. }
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g. 10.2, 3.1, 54.5 etc), you need to use float as the return type of
the method.
1. float get(){
2. return 10.2;
3. }
Now, you need to call the function, to get the value of the function.
16
Parameters in C Function
A c function may have 0 or more parameters. You can have any type of parameter in C
program such as int, float, char etc. The parameters are also known as formal arguments.
1. void hello(){
2. printf("hello c");
3. }
Calling a function in C
If a function returns any value, you need to call function to get the value returned from the
function. The syntax of calling a function in c programming is given below:
1. variable=function_name(arguments...);
1) variable: The variable is not mandatory. If function return type is void, you must not
provide the variable because void functions doesn't return any value.
3) arguments: You need to provide arguments while calling the C function. It is also known
as actual arguments.
17
Example of C function with no return statement
Let's see the simple program of C function that doesn't return any value from the function.
1. #include<stdio.h>
2. void hello(){
3. printf("hello c programming \n");
4. }
5. int main(){
6. hello();//calling a function
7. hello();
8. hello();
9. return 0;
10. }
Output
hello c programming
hello c programming
hello c programming
1. #include<stdio.h>
2. //defining function
3. int cube(int n){
4. return n*n*n;
5. }
6. int main(){
7. int result1=0,result2=0;
8.
9. result1=cube(2);//calling function
10. result2=cube(3);
11.
12. printf("%d \n",result1);
13. printf("%d \n",result2);
14. return 0;
15. }
Output
8
27
18
Call by value in C
In call by value, value being passed to the function is locally stored by the function parameter
in stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by reference in C
Here, address of the value is passed in the function, so actual and formal arguments shares the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
19
Let's try to understand the concept of call by reference in c language by the example given
below:
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Recursion in C
When function is called within the same function, it is known as recursion in C. The function
which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is know as tail
recursion. In tail recursion, we generally call the same function with return statement. An
example of tail recursion is given below.
1. recursionfunction(){
2. recursionfunction();//calling self function
3. }
20
Example of tail recursion in C
Let's see an example to print factorial number using tail recursion in C language.
1. #include<stdio.h>
2. int factorial (int n)
3. {
4. if ( n < 0)
5. return -1; /*Wrong value*/
6. if (n == 0)
7. return 1; /*Terminating condition*/
8. return (n * factorial (n -1));
9. }
10. int main(){
11. int fact=0;
12. fact=factorial(5);
13. printf("\n factorial of 5 is %d",fact);
14. return 0;
15. }
Output
factorial of 5 is 120
We can understand the above program of recursive method call by the figure given below:
Storage Classes in C
Storage classes are used to define scope and life time of a variable. There are four storage
classes in C programming.
auto
extern
static
register
21
Classes Place Value
auto RAM Garbage Local Within function
Value
extern RAM Zero Global Till the end of main program, May be
declared anywhere in the program
static RAM Zero Local Till the end of main program, Retains
value between multiple functions call
register Register Garbage Local Within function
Value
1) auto
The auto keyword is applied to all local variables automatically. It is the default storage class
that is why it is known as automatic variable.
1. #include<stdio.h>
2. int main(){
3. int a=10;
4. auto int b=10;//same like above
5. printf("%d %d",a,b);
6. return 0;
7. }
Output:
10 10
2) register
The register variable allocates memory in register than RAM. Its size is same of register size.
It has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
3) static
The static variable is initialized only once and exists till the end of the program. It retains its
value between multiple functions call.
The static variable has the default value 0 which is provided by compiler.
1. #include<stdio.h>
2. int func(){
3.
4. static int i=0;//static variable
5. int j=0;//local variable
22
6. i++;
7. j++;
8. printf("i= %d and j= %d\n", i, j);
9. }
10. int main() {
11. func();
12. func();
13. func();
14. return 0;
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
4) extern
The extern variable is visible to all the programs. It is used if two or more files are sharing
same variable or function.
C Array
Array in C language is a collection or group of elements (data). All the elements of c array
are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store marks
of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to
manage. For example we can not access the value of these variables with only 1 or 2 lines of
code.
Another way to do this is array. By using array, we can access the elements easily. Only few
lines of code is required to access the elements of array.
Advantage of C Array
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
23
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
1. data_type array_name[array_size];
1. int marks[5];
Here, int is the data_type, marks is the array_name and 5 is the array_size.
Initialization of C Array
A simple way to initialize array is by index. Notice that array index starts from 0 and ends
with [SIZE - 1].
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
24
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the
following code.
1. int marks[]={20,30,40,50,60};
Let's see the full program to declare and initialize the array in C.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
25
Two Dimensional Array in C
The two dimensional array in C language is represented in the form of rows and columns,
also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known as
multidimensional arrays.
1. data_type array_name[size1][size2];
1. int twodimen[4][3];
Initialization of 2D Array in C
A way to initialize the two dimensional array at the time of declaration is given below.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
26
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
1. functionname(arrayname);//passing array
First way:
Second way:
Third way:
You can also use the concept of pointer. In pointer chapter, we will learn about it.
1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
27
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }
Output
minimum number is 3
C Pointers
The pointer in C language is a variable, it is also known as locator or indicator that points to
an address of a value.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees etc. and used with arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.
28
Symbols used in pointer
Symbol Name Description
& (ampersand sign) address of operator determines the address of a variable.
* (asterisk sign) indirection operator accesses the value at the address.
Address Of Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to
display the address of a variable.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
value of number is 50, address of number is fff4
Declaring a pointer
Pointer example
An example of using pointers printing the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable i.e.
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
29
By the help of * (indirection operator), we can print the value of pointer variable p.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p);
7. printf("Value of p variable is %d \n",*p);
8. return 0;
9. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you can assign
NULL value. It will a better approach.
int *p=NULL;
1. #include<stdio.h>
2. int main(){
3. int a=10,b=20,*p1=&a,*p2=&b;
4.
5. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
6. *p1=*p1+*p2;
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
12. }
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10
30
C Pointer to Pointer
In C pointer to pointer concept, a pointer refers to the address of another pointer.
In c language, a pointer can point to the address of another pointer which points to the
address of a value. Let's understand it by the diagram given below:
1. int **p2;
Let's see an example where one pointer points to the address of another pointer.
As you can see in the above figure, p2 contains the address of p (fff2) and p contains the
address of number variable (fff4).
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. int **p2;//pointer to pointer
6. p=&number;//stores the address of number variable
7. p2=&p;
8. printf("Address of number variable is %x \n",&number);
9. printf("Address of p variable is %x \n",p);
10. printf("Value of *p variable is %d \n",*p);
11. printf("Address of p2 variable is %x \n",p2);
31
12. printf("Value of **p2 variable is %d \n",*p);
13. return 0;
14. }
15.
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
Pointer Arithmetic in C
In C pointer holds address of a value, so there can be arithmetic operations on the pointer
variable. Following arithmetic operations are possible on pointer in C language:
Increment
Decrement
Addition
Subtraction
Comparison
Incrementing Pointer in C
Increment operation depends on the data type of the pointer variable. The formula of
incrementing pointer is given below:
32 bit
64 bit
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
32
6. printf("Address of p variable is %u \n",p);
7. p=p+1;
8. printf("After increment: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. The formula of decrementing pointer is
given below:
32 bit
64 bit
1. #include <stdio.h>
2. void main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-1;
8. printf("After decrement: Address of p variable is %u \n",p);
9. }
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given
below:
33
32 bit
64 bit
Let's see the example of adding value to pointer variable on 64 bit OS.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+3; //adding 3 to pointer variable
8. printf("After adding 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, address of p is 3214864300. But after adding 3 with p variable, it is
3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we
were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2
byte memory in 32 bit OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. The formula of
subtracting value from pointer variable is given below:
32 bit
64 bit
Let's see the example of subtracting value from pointer variable on 64 bit OS.
1. #include<stdio.h>
34
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-3; //subtracting 3 from pointer variable
8. printf("After subtracting 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous
address value.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
35
It doesn't initialize memory at execution time, so it has garbage value initially.
1. ptr=(cast-type*)malloc(byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output:
calloc() function in C
36
1. ptr=(cast-type*)calloc(number, byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output:
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.
1. ptr=realloc(ptr, new-size)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
37
Let's see the syntax of free() function.
1. free(ptr)
C Strings
String in C language is an array of characters that is terminated by \0 (null character).
1. By char array
2. By string literal
1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As you know well, array index starts from 0, so it will be represented as in the figure given
below.
While declaring string, size is not mandatory. So you can write the above code as given
below:
1. char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
You can also define string by string literal in C language. For example:
1. char ch[]="javatpoint";
In such case, '\0' will be appended at the end of string by the compiler.
The only difference is that string literal cannot be changed whereas string declared by char
array can be changed.
38
String Example in C
Let's see a simple example to declare and print string. The '%s' is used to print string in c
language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[11]="javatpoint";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output:
Let's see a simple program to read and write string using gets() and puts() functions.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }
Output:
C String Functions
There are many important string functions defined in "string.h" library.
No Function Description
39
.
1) strlen(string_name) returns the length of string name.
2) strcpy(destination, source) copies the contents of source string to destination string.
3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
40
The strcat(first_string, second_string) function concatenates two strings and result is returned
to first_string.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
Output:
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
Output:
41
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
42
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
Output:
C String strstr()
The strstr() function returns pointer to the first occurrence of the matched string in the given
string. It is used to return substring from first match till the last character.
Syntax:
string: It represents the full string from where substring will be searched.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[100]="this is javatpoint with c and java";
5. char *sub;
6. sub=strstr(str,"java");
7. printf("\nSubstring is: %s",sub);
8. return 0;
9. }
Output:
C Math
C Programming allows us to perform mathematical operations through the functions defined
in <math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
43
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.
No Function Description
.
1) ceil(number) rounds up the given number. It returns the integer value which is greater
than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is less
than or equal to given number.
3) sqrt(number) returns the square root of given number.
4) pow(base, returns the power of given number.
exponent)
5) abs(number) returns the absolute value of given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
44
Structure in C
Structure in c language is a user defined datatype that allows you to hold different type of
elements.
It works like a template in C++ and class in Java. You can have different type of elements in
it.
Defining structure
The struct keyword is used to define structure. Let's see the syntax to define structure in c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
Here, struct is the keyword, employee is the tag name of structure; id, name and salary are
the members or fields of the structure. Let's understand it by the diagram given below:
45
Declaring structure variable
We can declare variable for the structure, so that we can access the member of structure
easily. There are two ways to declare structure variable:
1st way:
Let's see the example to declare structure variable by struct keyword. It should be declared
within the main function.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
2nd way:
Let's see another way to declare variable at the time of defining structure.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;
46
Which approach is good
But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the
structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in
main() fuction.
Let's see the code to access the id member of p1 variable by . (member) operator.
1. [Link]
C Structure example
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. [Link]=101;
11. strcpy([Link], "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", [Link]);
14. printf( "employee 1 name : %s\n", [Link]);
15. return 0;
16. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of structure in C language to store many employees information.
47
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. [Link]=101;
12. strcpy([Link], "Sonoo Jaiswal");//copying string into char array
13. [Link]=56000;
14.
15. //store second employee information
16. [Link]=102;
17. strcpy([Link], "James Bond");
18. [Link]=126000;
19.
20. //printing first employee information
21. printf( "employee 1 id : %d\n", [Link]);
22. printf( "employee 1 name : %s\n", [Link]);
23. printf( "employee 1 salary : %f\n", [Link]);
24.
25. //printing second employee information
26. printf( "employee 2 id : %d\n", [Link]);
27. printf( "employee 2 name : %s\n", [Link]);
28. printf( "employee 2 salary : %f\n", [Link]);
29. return 0;
30. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
Array of Structures in C
There can be array of structures in C programming to store many information of different
data types. The array of structures is also known as collection of structures.
Let's see an example of structure with array that stores information of 5 students and prints it.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
48
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }
Output:
Nested Structure in C
Nested structure in c language can have another structure as a member. There are two ways
to define nested structure in c language:
1. By separate structure
2. By Embedded structure
49
1) Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure
as a member. Let's see the code of nested structure.
1. struct Date
2. {
3. int dd;
4. int mm;
5. int yyyy;
6. };
7. struct Employee
8. {
9. int id;
10. char name[20];
11. struct Date doj;
12. }emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
We can define structure within the structure also. It requires less code than previous way. But
it can't be used in many structures.
1. struct Employee
2. {
3. int id;
4. char name[20];
5. struct Date
6. {
7. int dd;
8. int mm;
9. int yyyy;
10. }doj;
11. }emp1;
1. [Link]
2. [Link]
3. [Link]
50
C Nested Structure example
1. #include <stdio.h>
2. #include <string.h>
3. struct Employee
4. {
5. int id;
6. char name[20];
7. struct Date
8. {
9. int dd;
10. int mm;
11. int yyyy;
12. }doj;
13. }e1;
14. int main( )
15. {
16. //storing employee information
17. [Link]=101;
18. strcpy([Link], "Sonoo Jaiswal");//copying string into char array
19. [Link]=10;
20. [Link]=11;
21. [Link]=2014;
22.
23. //printing first employee information
24. printf( "employee id : %d\n", [Link]);
25. printf( "employee name : %s\n", [Link]);
26. printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", [Link],[Link],e1.d
[Link]);
27. return 0;
28. }
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
C Union
Like structure, Union in c language is a user defined datatype that is used to hold different
type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member
only. It shares memory of largest member.
51
Advantage of union over structure
It occupies less memory because it occupies the memory of largest member only.
Defining union
The union keyword is used to define union. Let's see the syntax to define union in c.
1. union union_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. union employee
2. { int id;
3. char name[50];
4. float salary;
5. };
52
C Union example
1. #include <stdio.h>
2. #include <string.h>
3. union employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for union
7. int main( )
8. {
9. //store first employee information
10. [Link]=101;
11. strcpy([Link], "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", [Link]);
14. printf( "employee 1 name : %s\n", [Link]);
15. return 0;
16. }
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only name
will have actual value.
File Handling in C
File Handling in c language is used to open, read, write, search or close file. It is used for
permanent storage.
Advantage of File
It will contain the data even after program exit. Normally we use variable or array to store
data, but data is lost after program exit. Variables and arrays are non-permanent storage
medium whereas file is permanent storage medium.
There are many functions in C library to open, read, write, search and close file. A list of file
functions are given below:
53
No Function Description
.
1 fopen() opens new or existing file
2 fprintf() write data into file
3 fscanf() reads data from file
4 fputc() writes a character into file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
The fopen() function is used to open a file. The syntax of fopen() function is given below:
You can use one of the following modes in the fopen() function.
Mod Description
e
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
The fclose() function is used to close a file. The syntax of fclose() function is given below:
54
C fprintf() and fscanf()
The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("[Link]", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("[Link]", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
55
Hello file by fprintf...
The fputc() function is used to write a single character into file. It outputs a character to a
stream.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("[Link]", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
[Link]
The fgetc() function returns a single character from the file. It gets a character from the
stream. It returns EOF at the end of file.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
56
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("[Link]","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
[Link]
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("[Link]","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
57
11. getch();
12. }
[Link]
hello c programming
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("[Link]","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }
Output:
hello c programming
C fseek()
C fseek() example
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write
data into file at desired location.
Syntax:
58
1. int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("[Link]","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
[Link]
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you
have to use stream many times.
Syntax:
Example:
File: [Link]
File: rewind.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("[Link]","r");
8.
9. while((c=fgetc(fp))!=EOF){
59
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }
Output:
As you can see, rewind() function moves the file pointer at beginning of the file that is why
"this is simple text" is printed 2 times. If you don't call rewind() function, "this is simple text"
will be printed only once.
C ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.
Syntax:
Example:
File: ftell.c
1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("[Link]", "r");
8. fseek(fp, 0, SEEK_END);
9.
10. length = ftell(fp);
11.
12. fclose(fp);
13. printf("Size of file: %d bytes", length);
14. getch();
60
15. }
Output:
C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.
#include
#define
#undef
#ifdef
#ifndef
#if
#else
#elif
#endif
#error
#pragma
61
C Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
1. #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros
Visit #define to see the full example of object-like and function-like macros.
C Predefined Macros
No Macro Description
.
1 _DATE_ represents current date in "MMM DD YYYY" format.
2 _TIME_ represents current time in "HH:MM:SS" format.
3 _FILE_ represents current file name.
4 _LINE_ represents current line number.
5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.
File: simple.c
1. #include<stdio.h>
2. int main(){
3. printf("File :%s\n", __FILE__ );
4. printf("Date :%s\n", __DATE__ );
5. printf("Time :%s\n", __TIME__ );
62
6. printf("Line :%d\n", __LINE__ );
7. printf("STDC :%d\n", __STDC__ );
8. return 0;
9. }
Output:
File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1
C #include
The #include preprocessor directive is used to paste code of given file into current file. It is
used include system-defined and user-defined header files. If included file is not found,
compiler renders error.
By the use of #include directive, we provide information to the preprocessor where to look
for the header files. There are two variants to use #include directive.
1. #include <filename>
2. #include "filename"
The #include <filename> tells the compiler to look for the directory where system header
files are held. In UNIX, it is \usr\include directory.
The #include "filename" tells the compiler to look in the current directory from where
program is running.
Let's see a simple example of #include directive. In this program, we are including stdio.h file
because printf() function is defined in this file.
1. #include<stdio.h>
2. int main(){
3. printf("Hello C");
4. return 0;
5. }
Output:
Hello C
#include notes:
Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>,
a//b is treated as filename.
63
Note 2: In #include directive, backslash is considered as normal text not escape sequence. So
in case of #include <a\nb>, a\nb is treated as filename.
Note 3: You can use only comment after filename otherwise it will give error.
C #define
The #define preprocessor directive is used to define constant or micro substitution. It can use
any basic data type.
Syntax:
1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }
Output:
3.140000
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }
Output:
C #undef
The #undef preprocessor directive is used to undefine the constant or macro defined by
#define.
Syntax:
1. #undef token
64
1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }
Output:
The #undef directive is used to define the preprocessor constant to a limited scope so that you
can declare constant again.
Let's see an example where we are defining and undefining number variable. But before
being undefined, it was used by square variable.
1. #include <stdio.h>
2. #define number 15
3. int square=number*number;
4. #undef number
5. main() {
6. printf("%d",square);
7. }
Output:
225
C #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code otherwise #else code is executed, if present.
Syntax:
1. #ifdef MACRO
2. //code
3. #endif
1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif
65
C #ifdef example
1. #include <stdio.h>
2. #include <conio.h>
3. #define NOINPUT
4. void main() {
5. int a=0;
6. #ifdef NOINPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Value of a: 2
But, if you don't define NOINPUT, it will ask user to enter a number.
1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifdef NOINPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11.
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Enter a:5
Value of a: 5
C #ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.
66
Syntax:
1. #ifndef MACRO
2. //code
3. #endif
1. #ifndef MACRO
2. //successful code
3. #else
4. //else code
5. #endif
C #ifndef example
1. #include <stdio.h>
2. #include <conio.h>
3. #define INPUT
4. void main() {
5. int a=0;
6. #ifndef INPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Enter a:5
Value of a: 5
But, if you don't define INPUT, it will execute the code of #ifndef.
1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifndef INPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11. printf("Value of a: %d\n", a);
67
12. getch();
13. }
Output:
Value of a: 2
C #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.
Syntax:
1. #if expression
2. //code
3. #endif
1. #if expression
2. //if code
3. #else
4. //else code
5. #endif
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
C #if example
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 0
4. void main() {
5. #if (NUMBER==0)
6. printf("Value of Number is: %d",NUMBER);
7. #endif
8. getch();
9. }
68
Output:
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. clrscr();
6. #if (NUMBER==0)
7. printf("1 Value of Number is: %d",NUMBER);
8. #endif
9.
10. #if (NUMBER==1)
11. printf("2 Value of Number is: %d",NUMBER);
12. #endif
13. getch();
14. }
Output:
C #else
The #else preprocessor directive evaluates the expression or condition if condition of #if is
false. It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
1. #if expression
2. //if code
3. #else
4. //else code
5. #endif
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
69
C #else example
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. #if NUMBER==0
6. printf("Value of Number is: %d",NUMBER);
7. #else
8. print("Value of Number is non-zero");
9. #endif
10. getch();
11. }
Output:
C #error
The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process.
C #error example
1. #include<stdio.h>
2. #ifndef __MATH_H
3. #error First include then compile
4. #else
5. void main(){
6. float a;
7. a=sqrt(7);
8. printf("%f",a);
9. }
10. #endif
Output:
1. #include<stdio.h>
2. #include<math.h>
3. #ifndef __MATH_H
70
4. #error First include then compile
5. #else
6. void main(){
7. float a;
8. a=sqrt(7);
9. printf("%f",a);
10. }
11. #endif
Output:
2.645751
C #pragma
The #pragma preprocessor directive is used to provide additional information to the compiler.
The #pragma directive is used by the compiler to offer machine or operating-system feature.
Syntax:
1. #pragma token
1. #pragma argsused
2. #pragma exit
3. #pragma hdrfile
4. #pragma hdrstop
5. #pragma inline
6. #pragma option
7. #pragma saveregs
8. #pragma startup
9. #pragma warn
1. #include<stdio.h>
2. #include<conio.h>
3.
4. void func() ;
5.
6. #pragma startup func
7. #pragma exit func
8.
9. void main(){
10. printf("\nI am in main");
11. getch();
71
12. }
13.
14. void func(){
15. printf("\nI am in func");
16. getch();
17. }
Output:
I am in func
I am in main
I am in func
To support command line argument, you need to change the structure of main() function as
given below.
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name
always.
Example
Let's see the example of command line arguments where we are passing one argument with
file name.
1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %s\n", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.\n");
8. }
9. else{
10. printf("First argument is: %s\n", argv[1]);
11. }
12. }
1. ./program hello
72
Run this program as follows in Windows from command line:
1. [Link] hello
Output:
Output:
But if you pass many arguments within double quote, all arguments will be treated as a single
argument only.
Output:
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.
73