0% found this document useful (0 votes)
16 views

UNIT 4 STRUCTURES AND UNION

Uploaded by

psaranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

UNIT 4 STRUCTURES AND UNION

Uploaded by

psaranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

VELAMMALENGINEERINGCOLLEGE

UNIT IV

Introduction - Need for Structure Data Type - Structure Definition – Structure Declaration –
Structures Within a Structure - Union - Programs using Structures and Unions - Storage Classes,
Pre-processor Directives.

STRUCTURES:
A Structure is a collection of one or more values of different data types, groupedtogether under a
single name. By using structures, we can make a group of variables,arrays, pointers etc.

Features of Structures:
❑ It is possible to copy the contents of all structure elements of different datatypes to another
structure variable of its type using assignment operator.
❑ Nesting of structure is possible.
❑ It is possible to pass structure elements to a function.
❑ It is possible to create structure pointers.

Declaration& Initialization of Structures:


Structures can be declared as follows:
struct struct_name
{
datatype variable1;
datatypevariable2;
}variable1, variable2;

Consider the following example to define a structure for an entity employee in c.


Example:
struct employee
{ int id;
char name[20];
float salary;
};

The following image shows the memory allocation of the structure employee that is defined in the above
example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure. Let's understand it by the diagram given below:

Declaring structure variable

We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.

1st way:

Let's see the example to declare the structure variable by struct keyword. It should be declared within the
main function.

struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.

struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure. .

2nd way:

Let's see another way to declare variable at the time of defining the structure.

struct employee
{ int id;
char name[50];
float salary;
}e1,e2;

Simpler Syntax for Initializing Structures

You can use a simpler syntax to initialize structures at the time of declaration:

struct employee e1 = {100,"Alice Smith", 25000};

This initializes e1 with the id 100, name "Alice Smith" and salary 25000 directly during declaration.

Example program:
#include<stdio.h>

struct student
{
int regno;
char name[30];
char branch[30];
int marks[10];
};

void main()
{
struct student s;
int total=0,i,n;
clrscr();
printf("Enter the reg.No");
scanf("%d",&s.regno);
fflush(stdin);
printf("\nEnter the name");
gets(s.name);
fflush(stdin);
printf("\nEnter the branch");
gets(s.branch);
printf("\nEnter the marks one by one\n");
for(i=0;i<7;i++)
{
scanf("%d",&s.marks[i]);
total=total+s.marks[i];
}
clrscr();
printf("\n\n STUDENTMARKPROCESSING \n");
printf("\n\tRegisterNo : %d",s.regno);
printf("\n\tNameoftheStudent :%s",s.name)
;printf("\n\tBranch :%s",s.branch);
printf("\n\tEnglish :%d",s.marks[0]);
printf("\n\tMathematics :%d",s.marks[1]);
printf("\n\tChemistry :%d",s.marks[2]);
printf("\n\tPhysics :%d",s.marks[3]);
printf("\n\tComputer Programming:%d",s.marks[4]);
printf("\n\tElectronicDevices :%d",s.marks[5]);
if(s.marks[0]>=50&&s.marks[1]>=50&&s.marks[2]>=50&&s.marks[3]>=50&&s.marks[4]>=50&&s.
marks[5]>=50&&s.marks[6]>=50)
printf("\n\tResult :PASS");
else
printf("\n\tResult :FAIL");
printf("\n\tTotal :%d",total);
getch();
}

OUTPUT:
Enter the reg.No 101
Enter the name aarthi
Enter the branch cse
Enter the marks one by one89
90
99
98
99
88

STUDENTMARKPROCESSING

Register No :101
Name of the Student :aarthi
Branch : cse
English :89
Mathematics :90
Chemistry :99
Physics :98
Computer Programming :99
Electronic Devices :88
Result :PASS
Total :641

Array of Structures in C
An array of structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of structures is also known as the
collection of structures.

Let's see an example of an array of structures that stores information of 5 students and prints it.

#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Structure Pointer

The structure pointer points to the address of a memory block where the Structure is being stored. Like
a pointer that tells the address of another variable of any data type (int, char, float) in memory. And here,
we use a structure pointer which tells the address of a structure in memory by pointing pointer
variable ptr to the structure variable.

Declare a Structure Pointer

The declaration of a structure pointer is similar to the declaration of the structure variable. So, we can
declare the structure pointer and variable inside and outside of the main() function. To declare a pointer
variable in C, we use the asterisk (*) symbol before the variable's name.

1. struct structure_name *ptr;


After defining the structure pointer, we need to initialize it, as the code is shown:
Initialization of the Structure Pointer
1. ptr = &structure_variable;

We can also initialize a Structure Pointer directly during the declaration of a pointer.

1. struct structure_name *ptr = &structure_variable;

As we can see, a pointer ptr is pointing to the address structure_variable of the Structure.
Access Structure member using pointer:

There are two ways to access the member of the structure using Structure pointer:

1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.


2. Using arrow ( -> ) operator or membership operator.

Program to access the structure member using structure pointer and the dot operator

Let's consider an example to create a Subject structure and access its members using a structure pointer
that points to the address of the Subject variable in C.

Pointer.c

#include <stdio.h>

// create a structure Subject using the struct keyword


struct Subject
{
// declare the member of the Course structure
char sub_name[30];
int sub_id;
char sub_duration[50];
char sub_type[50];
};

int main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = &sub; /* ptr variable pointing to the address of the structure variable sub */

strcpy (sub.sub_name, " Computer Science");


sub.sub_id = 1201;
strcpy (sub.sub_duration, "6 Months");
strcpy (sub.sub_type, " Multiple Choice Question");

// print the details of the Subject;


printf (" Subject Name: %s\t ", (*ptr).sub_name);
printf (" \n Subject Id: %d\t ", (*ptr).sub_id);
printf (" \n Duration of the Subject: %s\t ", (*ptr).sub_duration);
printf (" \n Type of the Subject: %s\t ", (*ptr).sub_type);
return 0;

Output:

Subject Name: Computer Science


Subject Id: 1201
Duration of the Subject: 6 Months
Type of the Subject: Multiple Choice Question

Program to access the structure member using structure pointer and arrow (->) operator

Let's consider a program to access the structure members using the pointer and arrow (->) operator in C.

Pointer2.c

#include <stdio.h>

// create Employee structure


struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};

// define the variables of the Structure with pointers


struct Employee emp1, emp2, *ptr1, *ptr2;

int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;

printf (" Enter the name of the Employee (emp1): ");


scanf (" %s", &ptr1->name);
printf (" Enter the id of the Employee (emp1): ");
scanf (" %d", &ptr1->id);
printf (" Enter the age of the Employee (emp1): ");
scanf (" %d", &ptr1->age);
printf (" Enter the gender of the Employee (emp1): ");
scanf (" %s", &ptr1->gender);
printf (" Enter the city of the Employee (emp1): ");
scanf (" %s", &ptr1->city);

printf (" \n Second Employee: \n");


printf (" Enter the name of the Employee (emp2): ");
scanf (" %s", &ptr2->name);

printf (" Enter the id of the Employee (emp2): ");


scanf (" %d", &ptr2->id);
printf (" Enter the age of the Employee (emp2): ");
scanf (" %d", &ptr2->age);
printf (" Enter the gender of the Employee (emp2): ");
scanf (" %s", &ptr2->gender);
printf (" Enter the city of the Employee (emp2): ");
scanf (" %s", &ptr2->city);

printf ("\n Display the Details of the Employee using Structure Pointer");
printf ("\n Details of the Employee (emp1) \n");
printf(" Name: %s\n", ptr1->name);
printf(" Id: %d\n", ptr1->id);
printf(" Age: %d\n", ptr1->age);
printf(" Gender: %s\n", ptr1->gender);
printf(" City: %s\n", ptr1->city);

printf ("\n Details of the Employee (emp2) \n");


printf(" Name: %s\n", ptr2->name);
printf(" Id: %d\n", ptr2->id);
printf(" Age: %d\n", ptr2->age);
printf(" Gender: %s\n", ptr2->gender);
printf(" City: %s\n", ptr2->city);
return 0;
}

Output:
Enter the name of the Employee (emp1): John
Enter the id of the Employee (emp1): 1099
Enter the age of the Employee (emp1): 28
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): California

Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles

Display the Details of the Employee using Structure Pointer


Details of the Employee (emp1)
Name: John
Id: 1099
Age: 28
Gender: Male
City: California

Details of the Employee (emp2) Name: Maria


Id: 1109
Age: 23
Gender: Female
City: Los Angeles

Structure within structure /Nested structure


A nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure.
Syntax:
struct name_1
{
member1;
member2;
.
.
membern;
struct name_2
{
member_1;
member_2;
.
.
member_n;
}, var1
} var2;
The member of a nested structure can be accessed using the following syntax:
Variable name of Outer_Structure.Variable name of Nested_Structure.data member to access
Example:
 Consider there are two structures Employee (depended structure) and another structure
called Organisation(Outer structure).
 The structure Organisation has the data members like
organisation_name,organisation_number.
 The Employee structure is nested inside the structure Organisation and it has the data
members like employee_id, name, salary.
For accessing the members of Organisation and Employee following syntax will be used:
org.emp.employee_id;
org.emp.name;
org.emp.salary;
org.organisation_name;
org.organisation_number;
Here, org is the structure variable of the outer structure Organisation and emp is the structure
variable of the inner structure Employee.
Different ways of nesting structure
The structure can be nested in the following different ways:
1. By separate nested structure
2. By embedded nested structure.
1. By separate nested structure: In this method, the two structures are created, but the dependent
structure(Employee) should be used inside the main structure(Organisation) as a member. Below is the
C program to implement the approach

// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>

// Declaration of the
// dependent structure
structEmployee
{
int employee_id;
char name[20];
int salary;
};

// Declaration of the
// Outer structure
struct Organisation
{
char organisation_name[20];
char org_number[20];

// Dependent structure is used


// as a member inside the main
// structure for implementing
// nested structure
struct Employee emp;
};
// Driver code
int main()
{
// Structure variable
struct Organisation org;

// Print the size of organisation


// structure
printf("The size of structure organisation : %ld\n",
sizeof(org));

org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name, "XXXXXXXX");
strcpy(org.org_number, "XXX123768");

// Printing the details


printf("Organisation Name : %s\n", org.organisation_name);
printf("Organisation Number : %s\n", org.org_number);
printf("Employee id : %d\n", org.emp.employee_id);
printf("Employee name : %s\n",org.emp.name);
printf("Employee Salary : %d\n", org.emp.salary);
}

Output:
The size of structure organisation : 68
Organisation Name : XXXXXXXX
Organisation Number : XXX123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000
2. By Embedded nested structure: Using this method, allows to declare structure inside a structure
and it requires fewer lines of code.
When the structure variable of the inner structure is declared at the end of the inner structure. Below is
the C program to implement this approach:

// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>

// Declaration of the main


// structure
struct Organisation
{
char organisation_name[20];
char org_number[20];

// Declaration of the dependent


// structure
struct Employee
{
int employee_id;
char name[20];
int salary;

// variable is created which acts


// as member to Organisation structure.
} emp;
};

// Driver code
int main()
{
struct Organisation org;

// Print the size of organisation


// structure
printf("The size of structure organisation : %ld\n",
sizeof(org));

org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name, "XXXXXXXX");
strcpy(org.org_number, "XXX123768");

// Printing the details


printf("Organisation Name : %s\n", org.organisation_name);
printf("Organisation Number : %s\n", org.org_number);
printf("Employee id : %d\n", org.emp.employee_id);
printf("Employee name : %s\n", org.emp.name);
printf("Employee Salary : %d\n", org.emp.salary);
}

Output:
The size of structure organisation : 68
Organisation Name : XXXXXXX
Organisation Number : XXX123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000

Typedef:

typedef is a keyword used in C language to assign alternative names to


existing datatypes.
Its mostly used with userdefined datatypes, when names of the datatypes become slightly complicated
to use in programs.
Syntax:
Typedef data_type new_name;

Example:

typedef int myint;

Now myint is an alias of int. From now on we can declare new int variables using myint
instead of int keyword.

myint i = 0;

This statement declares and initializes a variable i of typeint.


Typedef with a Structure:
Method 1
#include<stdio.h>

struct Point{
int x;
int y;
};
typedef struct Point Pt;

int main() {
Pt p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}

Method 2
#include<stdio.h>

// Define a structure named Point with two integer members: x and y

typedef struct Pt{


int x;
int y;
} Point;
int main() {
// Declare a variable named p1 of type Point
Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}

UNION:
Union is a variable, which is similar to the structure. It contains data elements ofdifferent data
types. The Union requires bytes that are equal to the number of bytesrequiredfor the
largestmembers.

The syntax is as follows:


union union_name {
datatype member1;
datatype member2;
...
};

Different Ways to Define a Union Variable

We need to define a variable of the union type to start using union members. There are two methods
using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.

Access Union Members

We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
The above method of accessing the members of the union also works for the nested unions.
var1.member1.memberA;
Here,
 var1 is a union variable.
 member1 is a member of the union.
 memberA is a member of member1.

Initialization of Union in C

The initialization of a union is the initialization of its members by simply assigning the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value at a given
instance of time.
Example of Union

// C Program to demonstrate how to use union


#include <stdio.h>
// union template or declaration
union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{

// defining a union variable


union un var1;

// initializing the union member


var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

return 0;
}

Output
T he value stored in member1 = 15

Size of Union
The size of the union will always be equal to the size of the largest member of the array.

// C program to find the size of union

#include <stdio.h>

union MyUnion {
int num1;
float num2;
};

int main()
{
union MyUnion UN;

printf("Size of union: %ld", sizeof(UN));

UN.num1 = 10;
printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);

UN.num2 = 10.34F;
printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);
return 0;
}

Output

Size of union: 4
Num1: 10, Num2: 0.000000
Num1: 1092972708, Num2: 10.340000

Difference between Structure & Union

S.No Structure Union


1. The keyword is struct. The keyword is union.
2. Memory allocation is done for all Memory allocation is done for the data
the data members in the member which requires maximum
structures. allocations.
Example. Example:
struct student unionstudent
{ {
int rollno; int rollno;
char name[5]; char name[5];
}s1; }
The memory allocation is 7Bytes. The memory allocation is
5Bytes

3. All the data members are Only the last stored data element is
available in the primary memory available in the primary memory at any
at any time of execution. time of execution.
4. Since memory is allocated for all Since memory is not allocated for all
the data members, nodata is the data member, only one data is
available and other data is
deleted in the primarymemory
Deleted from the primary memory
Storage Class Specifiers for Variables
• Variables are declared by the type of data they can hold
• The name of a variable is associated with a memory location within the computer where
the value assigned to the variable is stored in the form of bits.
• C provides four storage class specifiers to indicate where the variables
 would be stored
 how long they would exist
 what would be their region of existence
 what would be the default values
• Four storage class specifiers are
1. Automatic
2. External
3. Register
4. Static

• Storage class specifier precedes the declaration statement for a variable.


• The general form of the variable declaration statement with storage class specifier is
given as follows:
storage_class_specifier data_type variable_name;
The storage class – auto
By default, all variables declared within the body of any function are automatic.
To explicitly specify variable as automatic storage class keyword “auto” is used in the
declaration
For example, the following declaration statement within a function body
auto char any_alpha;
Variable stored : primary memory of the computer
Scope : limited within the function body
Existence : Vanishes when the function completes its specific task and returns to the
invoked main program
Default value :Garbage
Note – 1. If function body does not include the keyword auto, such declared variables
are implicitly specified as belonging to the automatic storage class
2. Local variables declared within nested blocks in a function belong by default to
the automatic storage class
#include <stdio.h>
int main(void)
{
auto int a =5;
printf(“\n a = %d”,a);
{
int a = 10;
printf(“\n a = %d”,a);
printf(“\n i = %d”,i);
}
printf(“\n a = %d”,a);
return 0;
}

Output
a = 5
a = 10
i = 4199232
a = 5

The storage class – register


Values stored in registers of the CPU are accessed in much lesser time than those stored in
the primary memory.
To allow the fastest access time for variables, the register storage class specifier is used.
The keyword for this storage class is “register”
For example, the following declaration statement within a function body
register char any_alpha;
In most C compilers, the register specifier can only be applied to int and char type variables;
however, ANSI C has broadened its scope.
Variable stored : registers of the CPU
Scope : Restricted within the region of a function or a block where it has been declared
Existence : exists as long as the function or block remains active.
Default value : unknown, which is interpreted as garbage.
• Note – 1. Storage class of a global variable cannot be specified as register.
2. Arrays cannot be stored in a registers but they may still receive preferential
treatment by the compiler depending on C compiler and the operating system
under which it is running

3. Global variables with register storage class are not allowed.


4. In C, it is not possible to obtain the address of a register variable by using ‘
&’ operator.
5. In addition, the only storage class specifier that can be used in a parameter
declaration is register.

Example : C program that demonstrates register variables


#include <stdio.h>
int main()
{
int m1 = 5;
register int m2 = 10;
printf("The value of m1 : %d ",m1);
printf("\nThe value of m2 : %d ",m2);
return 0;
}

Output
The value of m1 : 5
The value of m2 : 10

The storage class – static


Two kinds of variables are allowed to be specified as static variables:
 local variables (internal static variables)
 global variables (external static variables)
To specify a local variable as static, the keyword “static” precedes its declaration statement
For example, the following declaration statement within a function body
static int beta;

Difference between static local and static global variable

Static local variable Static global variable


Variable stored : permanent storage location in Variable stored : stored in the primary memory
the primary memory Scope : accessible by all functions in the
Scope : is usable within functions or blocks program file where these variables exist and are
where it is declared and preserves its previous declared. Not available to functions defined
value held by it between function calls or earlier in the same file or not accessible to
between block re-entries functions defined in other files although these
Existence : once a function is invoked, the static may use the extern keyword
local variable retains the value in it and exists as Existence : exist throughout the period of the
long as the main program is in execution main program execution
Default value : zero Default value : zero
Example : C program that demonstrates the use of the static variables and
functions

#include <stdio.h>
int main()
{
void show(void);
printf(“\n First Call of show()”);
show();
printf(“\n Second Call of show()”);
show();
printf(“\n Third Call of show()”);
show();
return 0;
}
void show(void)
{static int i;
printf(“\n i=%d”,i);
i++;}

Output
First Call of show()
i=0
Second Call of show()
i=1
Third Call of show()
i=2

Example : C program that demonstrates the use of the static variables and functions

#include <stdio.h>
void func(void);
static int count = 5; /* global variable */
int main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /*local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
Output
i is 6 and count is 4
i is 7 and count is 3

i is 8 and count is 2
i is 9 and count is 1

i is 10 and count is 0

The storage class – extern


When C program is large, it can be broken up into smaller programs.
After compiling, each program file can be joined together to form the large program.
These small program modules that combine together may need some variables that are used by
all of them.
External storage class variable are accessible to all the small program modules
These variables are global to all the small program modules that are formed as separate files.
The keyword “extern” for declaring such global variables
For example, the following declaration statement within a function body
extern int zeta;
Such global variables are declared like any other variable in one of the program modules while
the declaration of these variables is preceded with the keyword extern in all other combining
program modules (may be a function or a block).
Variable stored : primary memory
Scope : Accessible by small program modules that form the large program
Existence : exists as long as the program is in execution and their existence does not terminate
upon the exit of a function or a block or a program module from its state of execution
Default value : zero
Example : C program that demonstrates the use of the extern variables and functions
/* Program file: pgm1.c */ /* Program file : pgm2.c */
#include <stdio.h> extern int i;
#include “pgm2.c” /*link pgm2.c
*/
int i; /*external/global decl*/ /*fn definition of show()*/
void show(void);/*fn prototype*/
int main() void show() /*fn header */
{ {
i=10; printf(“\n Value of i in pgm2.c=%d”,i);
show();/*call to fn in pgm2.c*/ }
printf(“\n Value of i in pgm1.c=%d”,i);
return 0;
}

Output
Value of i in pgm2.c=10

Value of i in pgm1.c=10

Example : C program that demonstrates the use of the extern variables and functions

/* Program file: pgm1.c */ /* Program file : pgm2.c */


#include <stdio.h>
#include “pgm2.c” /*link pgm2.c */ extern int i;
int i; /*external/global decl*/ /*fn definition of show()*/
void show(void);/*fn prototype */
int main() void show() /*fn header ***/
{
show(); /*call to fn in pgm2.c */ {
printf(“\n Value of i in pgm1.c=%d”,i}); i = 20;
printf(“\n Value of i in pgm2.c=%d”,i);
return 0;}
}
Output
Value of i in pgm2.c=20

Value of i in pgm1.c=20

Pre-processor Directives

Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source
code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’
symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get
executed.
List of preprocessor directives in C
The following table lists all the preprocessor directives in C:
Preprocessor Directives Description

#define Used to define a macro

#undef Used to undefine a macro

#include Used to include a file in the source code program

Used to include a section of code if a certain


#ifdef
macro is defined by #define

#ifndef Used to include a section of code if a certain


Preprocessor Directives Description

macro is not defined by #define

#if Check for the specified condition

#else Alternate code that executes when #if fails

#endif Used to mark the end of #if, #ifdef, and #ifndef

These preprocessors can be classified based on the type of function they perform.
Types of C Preprocessors
There are 4 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives

1. Macros
In C, Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
Syntax of Macro Definition
#define token value
where after preprocessing, the token will be expanded to its value in the program.

// C Program to illustrate the macro


#include <stdio.h>

// macro definition
#define LIMIT 5

int main()
{
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}

return 0;
}

Output
0
1
2
3
4
In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The
word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-
colon to end.

Macros With Arguments


We can also pass arguments to macros. Macros defined with arguments work similarly to functions.
Example
#define foo(a, b) a + b
#define func(r) r * r

// C Program to illustrate function like macros


#include <stdio.h>

// macro with parameter


#define AREA(l, b) (l * b)

int main()
{
int l1 = 10, l2 = 5, area;

area = AREA(l1, l2);

printf("Area of rectangle is: %d", area);

return 0;
}

Output
Area of rectangle is: 50
We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it
replaces it with the statement (l*b). Not only this, but the values passed to the macro template AREA(l,
b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.

2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program.
The #include preprocessor directive is used to include the header files in the C program.
There are two types of files that can be included by the user in the program:
Standard Header Files
The standard header files contain definitions of pre-defined functions like printf(), scanf(), etc. These
files must be included to work with these functions. Different functions are declared in different header
files.
For example, standard I/O functions are in the ‘iostream’ file whereas functions that perform string
operations are in the ‘string’ file.
Syntax
#include <file_name>
where file_name is the name of the header file to be included. The ‘<‘ and ‘>’ brackets tell the compiler
to look for the file in the standard directory.
User-defined Header Files
When a program becomes very large, it is a good practice to divide it into smaller files and include them
whenever needed. These types of files are user-defined header files.
Syntax
#include "filename"
The double quotes ( ” ” ) tell the compiler to search for the header file in the source file’s directory.
3. Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a specific portion of
the program or to skip the compilation of some specific part of the program based on some conditions.
There are the following preprocessor directives that are used to insert conditional code:
1. #if Directive
2. #ifdef Directive
3. #ifndef Directive
4. #else Directive
5. #elif Directive
6. #endif Directive
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the
preprocessing of these directives is completed.
Syntax
#ifdef macro_name
// Code to be executed if macro_name is defined
#ifndef macro_name
// Code to be executed if macro_name is not defined
#if constant_expr
// Code to be executed if constant_expression is true
#elif another_constant_expr
// Code to be excuted if another_constant_expression is true
#else
// Code to be excuted if none of the above conditions are true
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally,
but if it is not defined, the compiler will simply skip this block of statements.
Example
The below example demonstrates the use of #include #if, #elif, #else, and #endif preprocessor directives.

//program to demonstrates the use of #if, #elif, #else,


// and #endif preprocessor directives.
#include <stdio.h>

// defining PI
#define PI 3.14159

int main()
{

#ifdef PI
printf("PI is defined\n");

#elif defined(SQUARE)
printf("Square is defined\n");
#else
#error "Neither PI nor SQUARE is defined"
#endif

#ifndef SQUARE
printf("Square is not defined");
#else
printf (“Square is defined" );
#endif

return 0;
}

Output
PI is defined
Square is not defined
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These are:
1. #undef Directive
2. #pragma Directive
1. #undef Directive
The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT”
statement will evaluate as false.
Example
The below example demonstrates the working of #undef Directive.

#include <stdio.h>

// defining MIN_VALUE

#define MIN_VALUE 10

int main() {
// Undefining and redefining MIN_VALUE
printf("Min value is: %d\n",MIN_VALUE);

//undefining max value


#undef MIN_VALUE

// again redefining MIN_VALUE


#define MIN_VALUE 20

printf("Min value after undef and again redefining it: %d\n", MIN_VALUE);

return 0;
}

Output
Min value is: 10
Min value after undef and again redefining it: 20
2. #pragma Directive
This directive is a special purpose directive and is used to turn on or off some features. These types of
directives are compiler-specific, i.e., they vary from compiler to compiler.

You might also like