CS3353 Unit2
CS3353 Unit2
S. Functions
No
1 Functions
Introduction
Types of Function Implementation
Passing Arguments(Parameters) To
Function
Call by Value
Call by Reference
Recursive Functions
Example Programs using functions
2 Pointers
Introduction --Definition --Declaration
Pointer Arithmetic
Pointers and arrays
Pointers and Strings
Pointers and Functions
3 Structures
Intro
Declaration—Initialization --Accessing
Programs using structures
Structure within Structure[Nested
Structure]
Arrays and Structures
Structure and functions
Pointers and structure
4 Union
5 Union using Structure
6 Storage classes
7 Pre-processor directives.
FUNCTION
A function is self contained program segment that carries out some specific, well defined task.
Need For Functions:
Many programs require a set of instructions to be executed repeatedly from several places in a program, and
then the repeated code can be placed within a single function, which can be accessed whenever it is required.
Dividing the program into separate well-defined functions facilitates each function to be written
and tested separately.
Understanding, coding, and testing multiple separate functions is easier than doing the same for one
big function main function.
A big program is broken into comparatively smaller functions.
Advantages of Functions
-Improves readability of code.
-Divides a complex problem into simpler ones
- Improves reuseability of code.
-Debugging errors is easier.
-modifying a program is easier.
Terms
A function f that uses another function g is known as the calling function, and
g is known as the called function.
The inputs that a function takes are known as arguments.
When a called function returns some result back to the calling function, it is
said to return
that result.
The calling function may or may not function,which can theot pass
parameters to the called function.
Function Declaration
Function Definition
Function Call
Function Definition
When a function is defined, space is allocated for that function in the memory. A function
definition comprises of two parts:
Function header
Function body
The syntax of a function definition can be given as:
void sum(int a,int b) int sum(int a,int b) Note that the number of
{ { arguments and the order of
Int c; Int c; arguments in the function
c=a+b; c=a+b; header must be
return(c); return(c); the same as that given in the
} } function declaration
statement.
Function Call
The function call statement invokes the function. When a function is invoked, the compiler
jumps to the called function to execute the statements that are a part of that function. Once
the called function is executed, the program control passes back to the calling function. A
function call statement has the following
Syntax-1:
function_name(variable1, variable2, ...);
If the return type of the function is not void then the following syntax can be used.
Syntax-2
Function Declaration
It is also called as function prototype. A function prototype consists of 4 parts
(1) Return type
(2) function name
(3) parameter list
(4) terminating (;) semicolin
Not passing Not passing arguments passing arguments & passing arguments &
arguments & not & returning some value not returning returning some value
returning anything anything
CASE-1 NOT PASSING ARGUMENTS & NOT RETURNING SOME VALUE
#include <stdio.h>
int sum( ); //FUNCTION DECLARATION
int main( )
{
int a,b,c;
scanf(“%d%d”,&a,&b); // get input values for a and b
c=x+y;
printf(“c=%d”,c);
}
Call by value
In Call by value, during function call actual parameter value is copied and
passed to formal parameter. Changes made to the formal parameters does not
affect the actual parameter.
Eg Program - C program to swap two numbers using call by value
#include<stdio.h>
int main()
{
int n1, n2;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
printf("In Main values before swapping: %d %d\n\n", n1, n2);
swap(n1, n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
void swap(int num1, int num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", num1, num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("In Function values after swapping: %d %d\n\n", num1, num2);
}
Output -
NOTE : In the above program swap() function does not alter actual parameter value. Before
passing the value of n1 and n2 to the swap() function, the C runtime copies the value of
actual parameter n1 and n2 to a temporary variable and passes copy of actual parameter.
Therefore inside the swap() function values has been swapped, however original value of n1
and n2 in main() function remains unchanged.
Call by reference
#include <stdio.h>
int main()
{ int n1, n2;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
printf("In Main values before swapping: %d %d\n\n", n1, n2);
swap(&n1, &n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
void swap(int * num1, int * num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", *num1, *num2);
temp = *num1;
*num1 = *num2;
*num2 = temp;
printf("In Function values after swapping: %d %d\n\n", *num1, *num2);
}
Output :-
Enter two numbers: 10 20
In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 20 10
In above example instead of passing a copy of n1 and n2, to swap() function. Operations
performed on formal parameter is reflected to actual parameter (original value). Hence, actual
swapping is performed inside swap() as well as main() function.
WRITE THESE SWAP PROGRAM(S) FOR YOUR EXAMS
Call by value
#include<stdio.h>
Void swap(int x,int y);
int main( )
Before swapping x and y
{ 10 20
int a = 10, b = 20 ; After swapping x and y
swap (a,b) ; // calling by value 20 10
printf ( "\n Before swapping x and y) ;
printf ( "\na = %d b = %d", a, b ) ;
return 0;
}
void swap( int x, int y)
{
int t ;
t =x;
x=y;
y= t ;
printf ( "\n After swapping x and y) ;
printf( "\nx = %d y = %d", *x,*y);
}
Call by reference
#include<stdio.h>
Void swap(int *x,int *y); Before swapping x and y
10 20
int main( ) After swapping x and y
{ 20 10
int a = 10, b = 20 ;
swap ( &a, &b ) ; // calling by reference
printf ( "\n Before swapping x and y) ;
printf ( "\na = %d b = %d", a, b ) ;
return 0;
}
void swap( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
printf ( "\n After swapping x and y) ;
printf( "\nx = %d y = %d", *x,*y);
}
Call by value Call by reference
When a function is called the actual values are When a function is called the address of
passed values(arguments) are passed
The parameters passed are normal variables The parameters passed are pointer variables
In call by value, actual arguments cannot be Modification to actual arguments is possible
modified. within from called function.
Actual arguments remain preserved and no Actual arguments will not be preserved.
chance of modification accidentally.
Calling Parameters: swap(a,b) Calling Parameters: swap(&a,&b)
Receiving parameters: void swap( int x, int y) Receiving parameters: void swap( int *x, int *y)
PASSING ARRAYS TO A FUNCTION
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
Advantage of Recursion
Disadvantage of Recursion
3*2 =6
2*1=2
1 * 1=1
Returns 1 as n value is 0
TOWER OF HANOI OF A NUMBER USING RECURSIVE FUNCTION
#include <stdio.h>
void hanoi(int n, char from, char to, char temp)
{
if (n == 1)
{
printf("\n Move Disk 1 from Peg %c to %c", from, to);
return;
}
hanoi(n-1, from, temp, to);
printf("\n Move disk %d from rod %c to rod %c", n, fr, tr);
hanoi(n-1, temp, to, from);
}
int main()
{
Printf(“ Towers of Honoi”);
int n;
printf(“\n Enter number of Disks”);
scanf(” %d ”,&n); // n implies the number of discs
hanoifun(n, 'A', 'C', 'B'); // A, B and C are the name of Peg
return 0;
}
To Transfer from disks from peg A to C taking help of B
Output
Move Disk 1 from Peg 1 to Peg 3.
Move Disk 2 from Peg 1 to Peg 2.
Move Disk 1 from Peg 3 to Peg 2.
Move Disk 3 from Peg 1 to Peg 3.
Move Disk 1 from Peg 2 to Peg 1.
Move Disk 2 from Peg 2 to Peg 3.
Move Disk 1 from Peg 1 to Peg 3.
Example: GCD of Two Numbers using Recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
STUDENTSFOCUS
Example: Fibonacci Series using Recursion
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main()
{
int i,f;
for (i = 0; i < 10; i++)
{
f= fibonacci(i);
printf("%d \n ",f);
}
return 0;
}
Output
0
1
1
2
3
5
8
13
21
34
Pointers in C Programming
Note :Here %u is a format specifier. It stands for unsigned, so it will only display positive values.
&-address of operator.
& is the “address of” operator. It is used to tell the C compiler to refer to the address of variables.
Address of any variable can’t be negative. This is the reason %u format specifier is used to print the
address of variables on the screen.
This is the second operator used for pointers. It is used to access the value present at some
address. And it is used to declare a pointer.
int x=10;
int *ptr; // Declaration of Pointer variable
ptr=&x; // Storing address of x variable in y pointer variable
Example program-1
#include<stdio.h>
void main()
{ 6 12
int a=6,b=12; 65524 65522
65524 65522
int *x,*y; 6 12
x=&a; 65524 65522
y=&b; 6 12
printf("%d t %d n",a,b);
printf("%u t %u n",&a,&b);
printf("%u t %u n",x,y);
printf("%d t %d n",*x,*y);
printf("%d t %d",(&a),(&b));
printf("%d t %d",*(&a),*(&b));
}
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/*address stored in pointer variable*/
printf("Address stored in ip variable: %x\n", ip );
/*access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
syntax
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable.
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr);
return 0;
}
output
The value of ptr is 0
Incrementing a Pointer(32-bit )
#include <stdio.h>
const int MAX = 3;
int main () {int
var[] = {10, 100,
200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
output
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Decrementing a Pointer(32-bit machine)
decreases its value by the number of bytes of its data type.
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
output
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
val = *p1+*p2;
printf("*p1+*p2 = %d\n", val);//point 1
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
return 0;
}
OUTPUT
p1 = 2680016
p2 = 2680012
*p1=5;
*p2=10;
*p1+*p2 = 15
p1-p2 = 1
p1++ = 2680020
p2-- = 2680008
STRUCTURES
Structure is a user-defined data type that can store related information (of different data types) together. The
major difference between a structure and an array is that an array can store only information of same data
type. A structure is therefore a collection of variables under a single name. The variables within a structure are
of different data types.
A structure is a collection of variables under a single name. These variables can be of
different types, Therefore, a structure is a convenient way of grouping together
several pieces of related information.
Complex hierarchies can be created by nesting structures.
Declaration/Initializing/Accessing
Nesting of Structures
Arrays of Structures
Structures and Pointers
Structures and Functions
A structure is declared by using the keyword struct followed by an optional structure tag
followed by the body of the structure. The variables or members of the structure are
declared within the body.
There are three different ways to declare and/or define a structure. These are
Variable structure
Tagged structure
Type-defined structure
1. A variable structure may be defined as follows.
struct
{
member_list
}variable_identifier;
struct
{
where. .... a,student1-are called as
int r_no;
char name[20]; structure variables
char course[20];
float fees;
} student1;
...
2.A tagged structure has been described earlier. It has the following format:
struct tag_name
{
member_list
}variable_identifier;
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
} stud1, stud2; Memory allocation
typedef keyword enables the programmer to create a new data type name by using an
existing data type.
When we precede a struct name with the typedef keyword, then the struct becomes a new
type. student becomes a new data type. To declare a variable of structure student, you may
write student stud1;
A structure can be initialized in the same way as other data types are initialized. Initializing a
structure means assigning some constants to the members of the structure.
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}struct_var = {constant1, constant2, constant3,...};
Example-1
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1 = {01, "Rahul", "BCA", 45000};
The members are accessed by relating them to the structure variable with a dot operator.
The general form of the statement for accessing a member of a structure is as follows.
stud1.r_no Stud2.r_no
stud1.name Stud2.name
stud1.course Stud2.course
Each member of a structure can be used just like a normal variable, but its name will be a bit longer.
A structure member variabl e is generally accessed using a '.' (dot) operator.
stud1.r_no = 01;
stud1.name = "Rahul";
stud1.course = "BCA";
stud1.fees = 45000;
To input values for data members of the structure variable stud1, we may write
scanf("%d", &stud1.r_no);
scanf("%s", stud1.name);
printf("%s", stud1.course);
printf("%f", stud1.fees);
Example-2 both initializing and accessing member data
struct {
float p, q,
int r;
} k = {k .p = 3.0, k.q = 7.9, k.r = 5};
Write a program using structures to read and display the information about a student
#include <stdio.h>
struct student
{
int roll_no;
char name[80];
float fees;
char DOB[80];
};
int main()
{
struct student stud1;
Output
Enter the roll number : 01
Enter the name : Rahul
Enter the fees : 45000
Enter the DOB : 25–09–1991
********STUDENT‟S DETAILS *******
ROLL No. = 01
NAME = Rahul
FEES = 45000.00
DOB = 25–09–1991
C program to read and print employee's record using structure
#include <stdio.h>
struct employee
{
char name[30];
int empId;
float salary;
};
int main()
{
struct employee emp; // declare structure variable
printf("\nEnter details :\n");
printf(“\n ************”);
printf("Name ?:");
scanf(“%s”,emp.name);
printf("ID ?:");
scanf("%d",&emp.empId);
printf("Salary ?:");
scanf("%f",&emp.salary);
Output
Enter details :
**********
Name ?:Mike
ID ?:1120
Salary ?:76543
#include <stdio.h>
struct employee
{
char grade;
int basic;
float allowance;
};
int main()
{
struct employee ramesh={„B‟, 6500, 812.5}; /* creating & initializing
member of employee */
Output:
vivek‟s grade is B
vivek‟s basic is Rs 6500
vivek‟s allowance is Rs
812.500000
Using Typedef :- A program that prints the weight of various sizes of fruits.
#include <stdio.h>
typedef struct fruits
{
float big;
float medium;
float small;
}fruits weight;
int main()
{
weight apples={200.75,145.5,100.25};
weight pears={150.50,125,50};
weight mangoes={1000, 567.25, 360.25};
printf(“\n\n apples: big size %f kg, medium size %f kg, small size %f kg”, apples.big,
apples.medium, apples.small);
printf(“\n\n pears: big size %f kg, medium size %f kg,small size %f kg”, pears.big,
pears.medium, pears.small);
printf(“\n\n mangoes: big size %f kg, medium size %f kg,small size %f kg”, mangoes.big,
mangoes.medium, mangoes.small);
return 0;
}
Output:
apples: big 200.75kg, medium 145.50kg, small 100.25kg
pears: big 150.50kg, medium 125.00kg, small 50.00kg
mangoes: big 1000kg, medium 567.25kg, small 360.25kg
Nesting of Structures
A structure can be placed within another structure. In other words, structures can contain other
structuresas members. A structure within a structure means nesting of structures.
In such cases, the dot operator in conjunction with the structure variables is used to access the
members of the innermost as well as the outermost structures.
#include <stdio.h>
struct DOB
{
int day;
int month;
int year;
};
struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date;
};
int main()
{
struct student stud1;
int main()
{
struct outer outvar; /* declaring structure_variable of outer */
outvar.out1= 2; /* assigning values to members */
outvar.out2= 10.57;
outvar.invar.in1= 2* outvar.out1; /* assigning values to members */
outvar.invar.in2= outvar.out2 + 3.65;
Output:
out1=2, out2= 10.57, in1=4, in2= 14.22
Write a program to read, display, add, and subtract two complex numbers.
#include <stdio.h>
#include <conio.h> Output
int main() ******** MAIN MENU *********
{ 1. Read the complex numbers
typedef struct complex 2. Display the complex numbers
{ 3. Add the complex numbers
int real; 4. Subtract the complex numbers
int imag; 5. EXIT
}COMPLEX;
COMPLEX c1, c2, sum_c, sub_c; Enter your option : 1
Enter the real and imaginary parts of the first complex
int option; number : 4 5
Enter the real and imaginary parts of the second complex
do number : 2 3
{ Enter your option : 2
printf("\n ******** MAIN MENU *********"); The first complex numbers is : 4+5i
printf("\n 1. Read the complex numbers"); The second complex numbers is : 2+3i
printf("\n 2. Display the complex numbers"); Enter your option : 3
printf("\n 3. Add the complex numbers"); The sum of two complex numbers is : 6+8i
printf("\n 4. Subtract the complex numbers"); Enter your option : 4
printf("\n 5. EXIT"); The difference between two complex numbers is : 2+2i
printf("\n Enter your option : ");
Enter your option : 5
scanf("%d", &option);
switch(option)
{
case 1:
printf("\n Enter the real and imaginary parts of the first complex number : ");
scanf("%d %d", &c1.real, &c1.imag);
printf("\n Enter the real and imaginary parts of the second complex number : ");
scanf("%d %d", &c2.real, &c2.imag);
break;
case 2:
printf("\n The first complex number is : %d+%di", c1.real,c1.imag);
printf("\n The second complex number is : %d+%di", c2.real,c2.imag);
break;
case 3:
sum_c.real = c1.real + c2.real;
sum_c.imag = c1.imag + c2.imag;
printf("\n The sum of two complex numbers is : %d+%di",sum_c.real, sum_c.imag);
break;
case 4:
sub_c.real = c1.real – c2.real;
sub_c.imag = c1.imag – c2.imag;
printf("\n The difference between two complex numbers
is :%d+%di", sub_c.real, sub_c.imag);
break;
}
}while(option != 5);
return 0;
}
ARRAYS OF STRUCTURES
Arrays of structures means that the structure variable would be an array of objects, each of which
contains the member elements declared within the structure construct.
struct student
Syntax {
struct struct_name int r_no;
{ char name[20];
data_type member_name1; char course[20];
data_type member_name2;
data_type member_name3; float fees;
....................... };
}; A student array can be declared by writing,
struct struct_name struct_var[index]; struct student stud[30];
Now, to assign values to the ith student of the class, we can write as
stud[i].r_no = 09;
stud[i].name = "RASHI";
stud[i].course = "MCA";
stud[i].fees = 60000;
int main()
{
int i;
struct boat ticket[4][3]={{“Vikram”,1,15.50},{“Krishna”,2,15.50},
{“Ramu”,3,25.50},{“Gouri”,4, 25.50 } };
printf(“\n passenger Ticket num. Fare”);
for(i=0;i<=3;i++)
printf(“\n %s %d %f ”, ticket[i].name,ticket[i].seatnum,ticket[i].fare);
return 0;
}
Output:
Passenger Ticket num. Fare
Vikram 1 15.500000
Krishna 2 15.500000
Ramu 3 25.500000
Gouri 4 25.500000
C program to generate salary slip of employees using structures
#include<stdio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;
void main()
{
int i, n ;
#include <stdio.h>
#include <string.h>
struct student
{
int roll_no;
char name[80];
int fees;
char DOB[80];
};
int main()
{
struct student stud[50];
int n, i, num, new_rollno;
int new_fees;
char new_DOB[80], new_name[80];
clrscr(); // clear screen
printf("\n Enter the number of students : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the roll number : ");
scanf("%d", &stud[i].roll_no);
for(i=0;i<n;i++)
{
printf("\n ********DETAILS OF STUDENT %d*******", i+1);
printf("\n ROLL No. = %d", stud[i].roll_no);
printf("\n NAME = %s", stud[i].name);
printf("\n FEES = %d", stud[i].fees);
printf("\n DOB = %s", stud[i].DOB);
}
printf("\n Enter the student number whose record has to be edited : ");
scanf("%d", &num);
stud[num].roll_no = new_rollno;
strcpy(stud[num].name, new_name);
stud[num].fees = new_fees;
strcpy (stud[num].DOB, new_DOB);
for(i=0;i<n;i++)
{
printf("\n ********DETAILS OF STUDENT %d*******", i+1);
printf("\n ROLL No. = %d", stud[i].roll_no);
printf("\n NAME = %s", stud[i].name);
printf("\n FEES = %d", stud[i].fees);
printf("\n DOB = %s", stud[i].DOB);
}
getch();
return 0;
} Output
Enter the number of students : 2
Enter the roll number : 1
Enter the name : kirti
Enter the fees : 5678
Enter the DOB : 9- 9- 99
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
int main()
{
POINT p1 = {2, 3}; Output
display(p1.x, p1.y); // function call The coordinates of the point are: 2 3
return 0;
}
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display(POINT);
int main()
{
POINT p1 = {2, 3};
display(p1);
return 0;
}
void display(POINT p)
{
printf("The coordinates of the point are: %d %d", p.x, p.y);
}
Passing Structure by Value
In this approach, the structure object is passed as function argument to the definition of
function, here object is representing the members of structure with their values.
Program
#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
struct Employee Emp = {1,"Kumar",29,45000};
Display(Emp);
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Passing Structure by Reference
In this approach, the reference/address structure object is passed as function argument to the
definition of function.
Program
#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Display(&Emp);
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Passing Structures through Pointers
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;
or,
struct struct_name *ptr;
The next thing to do is to assign the address of stud to the pointer using the address operator
(&).
ptr_stud = &stud;
(*ptr_stud).roll_no;
#include <stdio.h>
struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};
int main()
{
struct student stud1, *ptr_stud1;
ptr_stud1 = &stud1;
Storage class of a variable defines the lifetime and visibility of a variable. Lifetime means
the duration till which the variable remains active and visibility defines in which module of
the program the variable is accessible. They are:
1. Automatic
2. External
3. Static
4. Register
This variable is visible only within the function it is declared and its lifetime is same as the
lifetime of the function as well. This is the default storage class we have been using so far. It
applies to local variables only and the variable is visible only inside the function in which it is
declared and it dies as soon as the function execution is over. If not initialized, variables of
class auto contains garbage value.
The value is lost after the execution of function.
Syntax: auto datatype var_name1 [= value];
Example:
int var; // by default, storage class is auto
auto int var; // auto int j=10;
Example Program:
#include<stdio.h>
void display();
void main()
{
auto int a=10; //OR int a=10;
printf("\n A1 : %d",a);
display();
printf("\n A3 : %d",a);
}
void display()
{
int a=20; //OR auto int a=20;
printf("\n A2 : %d",a);
}
Output :
A1 : 10
A2 : 20
A3 : 10
2. External Storage Class
External storage class reference to a global variable declared outside the given program.
extern keyword is used to declare external variables. They are visible throughout the
program and its lifetime is same as the lifetime of the program where it is declared. This
visible to all the functions present in the program.
Example Program:
#include<stdio.h>
void display();
extern int a=10; //global variable
void main()
{
printf("\nA : %d",a);
increment();
display();
printf("\nA : %d",a);
}
void increment()
{
a = 20;
}
void display()
{
printf("\nA : %d",a);
}
Output :
A : 10
A : 20
A : 20
3. Static Storage Class
Static storage class ensures a variable has the visibility mode of a local variable but
lifetime of an external variable. It can be used only within the function where it is declared
but destroyed only after the program execution has finished. The default initial value of static
variable is 0. The value of a static variable persists between function calls
.
Syntax: static datatype var_name1 [= value];
Example: static int x = 101;
static float sum;
During multiple calling static variables retains their previous value.
#include<stdio.h>
void display();
void main() Output:
{
display(); A:1
display(); A:2
display(); A:3
}
void display()
{
static int a=1;
printf("\nA : %d",a);
a++;
}
In the above example, we does not use static keyword then the output will be :
Output : A : 1
A : 1
A : 1
4. Register Storage Class
Variables of class 'register' are stored in CPU registers instead of memory which
allows faster access. It has its lifetime and visibility same as automatic variable. The scope of
the variable is local to the function in which it is defined and it dies as soon as the function
execution is over. It contains some garbage value if not initialized. The purpose of creating
register variable is to increase access speed and makes program run faster. As register space
is very limited, so only those variables which requires fast access should be made register It
is declared as:
Syntax: register datatype var_name1 [= value];
Example: register int count
register char a;
C program to create automatic, global(extern) variables.
#include<stdio.h>
void main() Output :
{
register int a=10; A : 10
printf("\nA : %d",a);
}
PREPROCESSOR DIRECTIVES
The C Preprocessor is not part of the compiler but it extends the power of C
programming language. . The preprocessor provides the ability for the inclusion of header
files, macro expansions, conditional compilation, and line control. The preprocessors
functionality comes before compilation of source code and it instruct the compiler to do
required pre-processing before actual compilation. Working procedure of C program is
shown in Fig. 2.8. In general, preprocessor directives
begin with a # symbol
do not end with semicolon
are processed before compilation of source code
C Program
Preprocessor
Compiler
Linker
Executable
Code
Fig. 2.8 Working Procedure of C Program
There are four types of Preprocessor Directives supported by C language. They are:
File Inclusion directive
Macro Substitution directive
Conditional directive
Miscellaneous directive
List of all possible directives belong to each of the above is listed in Fig 2.9.
#include
It is used to include header file inside C Program. It checks for header file in current
directory, if path is not mentioned. To include user defined header file double quote is used
("") instead of using triangular bracket (< >).
Example:
#include <stdio.h> // Standard Header File
#include "big.h" // User Defined Header File
Preprocessor replaces #include <stdio.h> with the content of stdio.h header file.
#include "Sample.h" instructs the preprocessor to get Sample.h from the current directory
and add the content of Sample.h file.
Macro Substitution directive
#define
It is a simple substitution macro. It substitutes all occurrences of the constant and replace
them with an expression.There are two types of macro supported by C. They are:
1. Simple macro
2. macro with arguments
Simple macro
Syntax:
#define identifier value
Where
#define - is apreprocessor directive used for text substitution.
identifier - is an identifier used in program which will be replaced by value.(In
general the identifiers are represented in captital letters in order to
differentiate them from variable)
value -It is the value to be substituted for identifier.
Example:
#define PI 3.14
#define NULL 0
Example:
//Program to find the area of a circle using simple macro
#include <stdio.h>
#define PI 3.14
int main()
{
int radius;
float area;
printf(“Enter the radius of circle \n”);
scanf(“%d”, &radius);
area= PI * radius * radius;
printf(“Area of Circle=%f”, radius);
}
Output
Enter the radius of circle
10
Area of Circle = 314.000000
macro with arguments
#define Preprocessing directive can be used to write macro definitions with
parameters. Whenever a macro identifier is encountered, the arguments are substituted by the
actual arguments from the C program.
Data type definition is not necessary for macro arguments. Any numeric values like
int, float etc can be passed as a macro argument . Specifically, argument macro is not case
sensitive.
Example:
#define area(r) (3.14*r*r)
Example:
//Program to find the area of a circle using macro with arguments
#include <stdio.h>
#define area(r) (3.14*r*r)
int main()
{
int radius;
float a;
printf(“Enter the radius of circle \n”);
scanf(“%d”, &radius);
a= area(radius);
printf(“Area of Circle=%f”, a);
}
Output
Enter the radius of circle
10
Area of Circle = 314.000000
C Programming language defines a number of macros. Table 2.8 is the list of some
commonly used macros in C
Table 2.8 Predefined macros in C
Macro Description
NULL Value of a null pointer constant.
EXIT_SUCCESS Value for the exit function to return in case of successful
completion of program.
EXIT_FAILURE Value for the exit function to return in case of program
termination due to failure.
RAND_MAX Maximum value returned by the rand function.
FILE Contains the current filename as a string.
LINE Contains the current line number as a integer constant.
DATE Contains current date in "MMM DD YYYY" format.
TIME Contains current time in "HH:MM:SS" format.
Example:
NULL : 0
EXIT_SUCCESS : 0
EXIT_FAILURE : 1
RAND_MAX : 32767
File Name : BuiltinMacro.c
DATE : Aug 16 2017
Line : 12
Conditional directive
The Conditional directives permit to include a block of code based on the result of
conditional expression.
Syntax:
#if <expression>
statements;
#elif <expression>
statements;
#else
statements;
#endif
Where
Expression represents a condition which produces a boolean value as a result.
Conditional directive is similar to if else condition but it is executed before
compilation. Condition_Expression must be only constant expression.
Example:
#undef
Syntax:
#undef <Constant>
Example:
#include<stdio.h>
#define P 100
#ifdef P
#undef P
#define P 30
#else
#define P 100
#endif
int main()
{
printf("%d",P);
return 0;
}
Output
30
Miscellaneous directive
STUDENTSFOCUS
The pragma directive is used to access compiler-specific preprocessor
extensions. Each pragma directive has different implementation rule and use . There
are many type of pragma directive and varies from one compiler to another compiler .If
compiler does not recognize particular pragma then it ignores the pragma statement
without showing any error or warning message.
Example:
#pragma sample
int main()
{
printf(“Pragma verification “);
return 0;
}
Output
Pragma verification
1. #pragma startup
2. #pragma exit
3. pragma warn
4. #pragma option
5. #pragma inline
6. #pragma argsused
7. #pragma hdrfile
8. #pragma hdrstop
9. #pragma saveregs
#error
The #error directive causes the preprocessor to emit an error message. #error
directive is used to prevent compilation if a known condition that would cause the
program not to function properly.
Syntax:
#error “message”
Example:
int main()
{
#ifndef PI
#error "Include PI”
#endif
}
return 0; STUDENTSFOCUS
Output
compiler error --> Error directive : Include PI
#line
It tells the compiler that next line of source code is at the line number which has been
specified by constant in #line directive
Syntax:
#line <line number> [File Name]
Where Output
File Name is optional 700
Example: 701
int main() 702
{
#line 700
printf(Line Number %d”, LINE );
printf(Line Number %d”, LINE );
printf(Line Number %d”, LINE );
return 0;
}