0% found this document useful (0 votes)
43 views23 pages

Unit V Structures and Unions: Y. Arockia Raj, Ap / Cse Psna College of Engineering and Technology

The document discusses structures in C programming. It defines a structure as a collection of variables of different data types grouped together under a single name. Structures allow programmers to define new data types that can contain multiple pieces of related data. The document covers defining and declaring structure variables, initializing structures, accessing structure members, operations on structures like assignment and using sizeof, and anonymous structures.
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)
43 views23 pages

Unit V Structures and Unions: Y. Arockia Raj, Ap / Cse Psna College of Engineering and Technology

The document discusses structures in C programming. It defines a structure as a collection of variables of different data types grouped together under a single name. Structures allow programmers to define new data types that can contain multiple pieces of related data. The document covers defining and declaring structure variables, initializing structures, accessing structure members, operations on structures like assignment and using sizeof, and anonymous structures.
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/ 23

Unit V

STRUCTURES AND UNIONS


Introduction – need for structure data type – structure definition – Structure
declaration – Structure within a structure - Union - Programs using
structures and Unions – Storage classes, Pre-processor directives.

Introduction
C Language provides the flexibility to create the new data types are
known as user defined data types, can be created by using structures, union
and enum.

Structures

A Structure is a collection of variables of different data types under a


single name.
[ i.e., structure is a collection of dissimilar data items]
It is a user defined data type.

There are three aspects of working with structures.


1. Defining a structure -> ie Creating a new type
2. Declaring variables and constants of the newly created type.
3. Using and performing operations on the objects of the structure type.

Defining a structure
The general form of structure definition is,
struct structure_name struct structure_name
{ {
datatype element1; datatype element1;
datatype element2; datatype element2;
. .
. .
datatype elementN; datatype elementN;
}; }var1, var2;
struct structure_name var1, var2;
var1, var2 -> structure variables

Example
struct student struct student
{ {
char grades; char grades;
int rno; int rno;
float avg; float avg;
}; }s1;
struct student s1;

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 1


The important points about structure definition are as follows:

Can group different data type elements in the structure.


A structure definition consists of the keyword ‘struct‟ followed by
structure_name and the structure declaration list(set of elements).
The structure definition defines a new type, known as structure
type.
Structure name is an identifier; hence it follows the rules of an
identifier.
A structure declaration list cannot contain a member of void type or
incomplete type or function type.
A structure definition can have an infinite number of members
(elements).
A structure can contain a pointer to itself

struct node
{
int data;
struct node *ptr;
};
Shorthand declaration used to declare structure members of the same
type.
struct example struct example
{ {
int a; shorthand int a, b;
int b; declaration }
}

The name of a structure member can be the same as the structure tad-
name.
struct book
{
char book[20];
float price;
}b1;
It is important to note that a structure definition does not reserve any
space in the memory.
It is not possible to initiate the structure members during structure
definition.
struct book
{
char book[20] ="Computer
Programming";
float price=430.50;
}b1;

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 2


Anonymous structure type
If a structure definition does not contain a structure name, the created
structure type is unnamed. The unnamed structure type is also known as
anonymous structure type.
struct
{
int x;
int y;
};
Declaring structure objects
i.e declaring structure variables. Structure variables are declared
in two ways.
1. During structure definition
2. After structure definition

1. During structure definition 2. After structure definition


struct student struct student
{ {
char grades; char grades;
int rno; int rno;
float avg; float avg;
}s1; };
struct student s1;

Initialization of a structure
Structure elements can be initialized as follows,
struct student struct student
{ {
int rno; int rno;
int tot; int tot;
float avg; float avg;
}; }s1={101, 486,97.20};
struct student s1={101, 486, 97.20};
The amount of the memory space allocated to it is equal to the sum of
the memory space required by all of its members.
struct student struct student
{ {
char grades; 1 char name[20];
int rno; 2 int tot;
float avg; 4 float avg;
}s1; }s1;
Size of the structure =7 bytes Size of the structure = 26 bytes
(1+2+4) (20+2+4)
printf(“%d”, sizeof(struct student)); // it prints the size of structure

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 3


A structure object declaration can optionally have a storage class
specifier [like auto , static, extern, register, typedef…]

Operations on structures

The operations that can be performed on an object (ie variable or


constant) of a structured type are classified into two categories.

1. Aggregate operations
2. Segregate operations

Aggregate operations

An aggregate operation treats an operand as an entity and operates on


the entire operand as whole instead of operating on its constituent members.
Four aggregate operations are,

1. Accessing members of an object of a structure type.


2. Assigning a structure object to a structure variable
3. Address of a structure object
4. Size of a structure

1. Accessing members of an object of a structure type

The member of a structure object can be accessed by using,


a. Direct member access operator (ie . dot operator)
b. Indirect member access operator (ie -> arrow operator)

struct student The structure members are accessed as


{ s1.rno, s1.avg and
int rno; s2.rno, s2.avg;
float avg;  It uses dot operator with syntax is,
}s1,s2;  Structure_variable . member_name

Arrow operator (->) used with structure pointer.

struct student s1; The structure members are accessed as


struct student *s2;  By using  By using
dot arrow
s2=&s1; operator operator
s1.rno; s2->rno;
s2.avg; s2->avg;

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 4


2. Assigning a structure object to a structure variable
A structure variable can be assigned with or initialized with a structure
object. (ie variable or constant) of the same structure type.

#include<stdio.h>
struct student
{
int rno;
int tot;
float avg;
};
main()
{
struct student s1={101,426,85.20};
struct student s2=s1;
printf("%d%d%f",s1.rno,s1.tot,s1.avg);
printf("%d%d%f",s2.rno,s2.tot,s2.avg);
getch();
}

output: 101 426 85.60


101 426 85.60

3. Address of structure object


The address of operator when applied on a structure object
gives the base address (strating address).

struct student
{
int rno; rno avg
float avg; 3000 3002
}s;

printf(“%u”,&s); Gives the output as 3000 ie., the starting address.

4. Use of sizeof operator on structures

When the sizeof operator is applied to an operand of a structure type,


the result is the total number of bytes that an object of such type will
occupy in the memory.

struct student Printf(“%d”,sizeof(struct student));


{
int rno; Gives 6 (in bytes).
float avg;
}s;
Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 5
Segregate operations

A segregate operations operates on the individual members of a


strcture object. The individual members of a structure object. The individual
members of a structure object like normal object ( ie variable & constants).

struct student Example operations on individual members


{ includes,
int rno; s.rno =101;
float avg; s.avg = 90+5;
}s;

Pointers to structures

It is possible o create a pointer to a structure type. It can store the


address of a structure variable.

struct stud
{
……….
……….
}s1,*s2; s1 -> structure variable
s2=&s1; s2-> structure pointer

Advantages of pointer to structures includes,

i. It is easier to manipulate the pointers to structures than manipulating


structures themselves.
ii. Some data structures (linkedlist, trees,..) use the structures containing
pointers to structures.
iii. Passing a pointer to a structure as an argument to a function is
efficient as compared to passing a structure to a function.

Example:
// student details using pointers to structures

#include<stdio.h>
struct student
{
int rno;
int m1,m2,m3;
float avg;
};

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 6


void main()
{
struct student s1={101,80,90,90,86.66};
struct student *s2=&s1;
clrscr();
printf("details are ");
printf("%d%d%d%d%f", s2->rno,s2->m1,s2->m2,s2->m3,s2->avg);
hetch();
}

output:

datails are
101 80 90 90 86.66

Array of structures

It is possible to create an array whose elements are of structure type.


Such an array is known as an array of structures.
If there is a need to access number of structure variable, can use
structure variable as array.
struct student
{
int rno; Here the structure variable „s‟ can
float avg; store 50 students details.
}s[50];

In such cases the structure elements are accesses with for loop as
s[i].rno,s[i].avg
Ie for(i=0;i<50;i++)
scanf(“%d “%f”,&s[i].rno,&s[i],avg);
example:

//student details using structures


#include<stdio.h>
#include<conio.h>

struct student
{
char name[20];
int rno,m1,m2,m3,m4,m5,m6,tot;
float avg;
};

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 7


void main()
{
struct student s[60],temp;
int n,i,j;
clrscr();

printf("Enter the number of students \n");


scanf("%d",&n);

printf("Enter Name, Regno, 6 marks of n students \n");


for(i=0;i<n;i++)
{
scanf("%s%d%d%d%d%d%d%d",s[i].name,&s[i].rno,&s[i].m1,&s[i].m2,&s[i].m
3,&s[i].m4,&s[i].m5,&s[i].m6);
s[i].tot=s[i].m1+s[i].m2+s[i].m3+s[i].m4+s[i].m5+s[i].m6;
s[i].avg=s[i].tot/6;
}

printf("\n\t\t Student Mark List \n");


printf("\nName\t\tRegNo\tTotal\tAverage\n");
printf("******************************************\n");
for(i=0;i<n;i++)
{
printf("\n %s\t\t%d\t%d\t%0.2f",s[i].name,s[i].rno,s[i].tot,s[i].avg);
}

//students mark list sorted on Total


for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(s[i].tot<s[j].tot)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("\n\t\t student marklist based on sorted order of Total\n");
printf("\nName\t\tRegNo\tTotal\tAverage\n");
printf("******************************************\n");
for(i=0;i<n;i++)
{
printf("\n %s\t\t%d\t%d\t%0.2f",s[i].name,s[i].rno,s[i].tot,s[i].avg);

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 8


}
getch();
}

Output:

Example 2
//employee details using structures
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[10];
int eid,basic;
int hra,ta,da,pf,netsal;
};

void main()
{
int n,i,j;
struct employee e[50],temp;
clrscr();
printf("Enter the number of employees \n");
scanf("%d",&n);
printf("Enter Name, Emp id & Basic pay \n");

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 9


for(i=0;i<n;i++)
{
scanf("%s%d%d",e[i].name,&e[i].eid,&e[i].basic);
e[i].ta=e[i].basic*0.15;
e[i].hra=e[i].basic*0.12;
e[i].da=e[i].basic*0.08;
e[i].pf=e[i].basic*0.1;
e[i].netsal=e[i].basic+e[i].ta+e[i].da+e[i].hra-e[i].pf;
}

printf("\n\n \t Employee Details \n");


printf("\nName\t\tEmpID\t Basic Sal\t NetSalary \n");
printf("****************************************************\n");
for(i=0;i<n;i++)
{
printf("\n%s\t\t%d\t\t%d\t \t%d",e[i].name,e[i].eid,e[i].basic,e[i].netsal);
}

// To sort the employees based on salary


for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(e[i].netsal<e[j].netsal)
{
temp=e[i];
e[i]=e[j];
e[j]=temp;
}
}
}
printf("\n\n \t Employee Details Sorted on Salary\n");
printf("\nName\t\t****EmpID\t Basic Sal\t NetSalary \n");
printf("**********************************************\n");
for(i=0;i<n;i++)
{
printf("\n%s\t\t%d\t\t%d\t \t%d",e[i].name,e[i].eid,e[i].basic,e[i].netsal);
}
getch();
}

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 10


output

Write a C program to accept records of 20 states using array of structures.


The structure should contain name of the state and number of engineering
colleges, medical colleges, management colleges, science colleges. Calculate
and display the total number of colleges in each state and the state which is
having the highest number of colleges.
#include<stdio.h>
#include<conio.h>
struct state
{
char name[20];
int nengg,nmed,nmgt,nsci,tot;
}s[20],max;

void main()
{
int i;
clrscr();
printf("Enter state name, no of engg colleges, meedical colleges,
management colleges, science colleges\n");
for(i=0;i<20;i++)
{
scanf("%s%d%d%d%d",s[i].name,&s[i].nengg,&s[i].nmed,&s[i].nmgt,
&s[i].nsci);

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 11


s[i].tot=s[i].nengg+s[i].nmed+s[i].nmgt+s[i].nsci;
}

printf("\nstate name\t Total colleges\n ");


printf("********************************\n");
for(i=0;i<20;i++)
{
printf("%s\t\t%d",s[i].name,s[i].tot);
printf("\n");
}
// to calculate the state wit max colleges
for(i=1;i<20;i++)
{
max.tot=s[0].tot;
if(max.tot<s[i].tot)
{
max.tot=s[i].tot;
strcpy(max.name,s[i].name);
}
}
printf("The state %s has maximum colleges as %d",max.name,max.tot);
getch();
}

Nested Structures (Structure within a structure)

A structure can be nested within another structure. Nested structure


are used to create complex data types.

A nested structure contains the members of other structure types. The


structure types used in the structure definition must be complete.
It is possible to define a structure type within the declaration list of
another structure type definition.

struct namelist
{
........
};
struct phonebook //nested structure
{
struct namelist name;
........
};

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 12


//Program for Structure within a structure (nested structure)
#include<stdio.h>
#include<conio.h>
struct namelist
{
char fname[20];
char lname[10];
};
struct phonebook
{
struct namelist name;
char mobile[15];
};
void main()
{
struct phonebook p1,p2;
clrscr();
printf("\n Enter person 1 details");
printf("\n Enter first name of p1");
scanf("%s",p1.name.fname);
printf("\n Enter last name of p1");
scanf("%s",p1.name.lname);
printf("\n Enter mobile number");
scanf("%s",p1.mobile);

printf("\n Enter person 2 details");


printf("\n Enter first name of p2");
scanf("%s",p2.name.fname);
printf("\n Enter last name of p1");
scanf("%s",p2.name.lname);
printf("\n Enter mobile number");
scanf("%s",p2.mobile);
printf("\n Records in phonebook \n ");
printf("\n Name \t Mobile no \n");
printf("\n %s %s \t %s",p1.name.fname,p1.name.lname,p1.mobile);
printf("\n %s %s \t %s",p2.name.fname,p2.name.lname,p2.mobile);
getch();
}

output:
Enter person 1 datails
Enter first name of p1 name1
Enter last name of p1 d
Enter mobile number 123456
Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 13
Enter person 2 datails
Enter first name of p2 name2
Enter last name of p2 z
Enter mobile number 654321

Records in phonebook
Name Phonebook
name1 d 123456
name2 z 654321

Union
• Union is a collection of elements of different data type under a single
name.
• It is a user defined data type.
• Declared with the keyword union followed by union name and set of
elements.
 All the aspects and the operations of union are same that of structures.
The only difference between them is in terms of storage of their
memories.
 In structure, a separate memory is allotted to each member, while in
unions, all the members of an object share the same memory.

Declaring a union
Syntax :
union unionure_name
{
datatype element 1;
-
datatype element n;
};
union union_name var1,var2…var n; //Var1, var2 - union variables
Example
union student or union student
{ {
char grade; char grade;
int rno; int rno;
float avg; float avg;
}; } s1,s2;
union student s1,s2;
• Union must end with a semicolon.
• Union elements must be accessed with union variable with dot(.)
operator
eg : s1.rno, s1.m1, s1.avg
s2.rno, s2.m1, s2.avg

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 14


• The size of a union is equal to the size of the largest data member. ie C
compiler allocates just enough space for the largest data member.

• The size of the above union is 4 bytes [ maximum sized elements ]

2000 2001 2002 2003

grade
rno
avg

Address of union object


The member a union object are stored in the memory in such a
way that they overlap each other. Ie all the member of a union
object start from the same memory location, which in fact, is the
same as the starting address of union object.
For example in the previous example the address of the element
grade, rno, avg is 2000.

Initialization of union
Since the members of a union object share the same memory, the union
object can hold the value of only one of its member at a time. Hence while
initializing a union object, it is allowed to initialize its first member only.
union student
{ int rno;
int m1,m2,m3;
float avg;
};
union student s={101};

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 15


comparison between structure and union :

Structure union
Structure is a collection of elements Union is a collection of elements of
of different data type under a single different data type under a single
name. name.
It is a user defined data type. It is a user defined data type.
Declared with the keyword struct Declared with the keyword union
followed by structure name and set followed by union name and set of
of elements elements
Each member has its own storage All the members share the same
space memory space to store the values
It can handle all the members at the It can handle only one element at a
same time time
Example struct student union student
{ char grade; { char grade;
int rno; int rno;
float avg; float avg;
} s; } s;
size of the above structure is 7 size of the union is 4 bytes [
bytes[1+2+4] maximum sized element]
More storage space is required. Less storage space is required.
It may be initialized with all its Only its first member may be
members initialized
Example struct stud union stud
{ int rno; { int rno;
float avg; float avg;
}; };
struct stud s={101,95.50}; union stud s={101}; (only 1st
element)

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 16


/*Program for student details using union */
#include<stdio.h>
#include<conio.h>
union student
{
int regno;
int m1,m2,m3,m4,m5,m6;
}s[2];
void main()
{
int i,tot;
float avg;
clrscr();
printf("Enter regno and 6 marks of 2 students");
for(i=0;i<2;i++)
{
printf("\n Enter the register no ");
scanf("%d",&s[i].regno);
printf("\n Enter 6 marks");
scanf("%d%d%d%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3,&s[i].m4,&s[i].m5,&s[i]
.m6);
tot=s[i].m1+s[i].m2+s[i].m3+s[i].m4+s[i].m5+s[i].m6;
printf("\nTotal marks : %d",tot);
avg=tot/6;
printf("\nAverage : %f",avg);
}
getch();
}
output

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 17


Storage classes
Every identifier not only has a data type but also has a storage class. To
fully define an identifier, one needs to mention not only its data type, but also
its storage class.
If any storage class is not specified in a declaration statement, the
compiler assumes the default storage class depending upon the scope in
which the declaration is made.
The storage class of an identifier determines
o Object is stored in the memory or CPU register
o What the initial value of the object
o Whether lifetime is local or global
o What the linkage of a function or identifier would be.

C language provides the following storage class specifies

1. auto
2. static
3. extern
4. register
5. typedef

General syntax of a declaration statement is,

Storage_class data_type variable_name;


Auto/static/extern/register

auto

 Automatic variables
 The variables without any storage class specification are called as auto
variables. They are called automatic because their memory space is
automatically allocated as the variable is declared.
 Auto variables are stored in main memory.
 Scope of auto variable is local lifetime.
 Auto variable will have a garbage value.
 The storage class auto cannot be used with global variables.
o All the variables are by default auto variables.
Syntax:
auto datatype var1,var2,…varN;

Example:
auto int a,b; ie int a,b;
auto float x,y; ie float x,y;

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 18


//example program using auto
#include<stdio.h>
#include<conio.h>
void main()
{
auto int a=10;
clrscr();
printf("a is %d",a);
getch();
}

output
a is 10

static

The contents of static variables are permanent within function. ie the


contents of the variable will be retained throughout the program.
Static variable are stored in main memory.
 It can also be used both with the identifiers in the local scope and
global scope.
 Static variables are initialized only once. The variables will not be
reinitialized.
 Default value of static variable is „zero‟.
 Static storage specifier cannot be used as the arguments for this
functions.
 static variables are initialized to zero.

Syntax:
static datatype var1,var2…………….var n;
Example:
static int a;

#include<stdio.h> #include<stdio.h>
void fun(); \\ function declaration void fun(); \\ function declaration
void main() void main()
{ {
int i=1; int i=1;
while(i<=5) while(i<=5)
{ {
fun(); \\ function call fun(); \\ function call
i++; i++;
} }
} }
void fun() void fun()

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 19


{ {
int a=10; static int a=10;
printf(“%d”,++a); printf(“%d”,++a);
} }
Output: 11 11 11 11 11 Output: 11 12 13 14 15
=>even though the function fun() called 5 times the initialization of
a(i.e a=10 ) will be done only once.

extern

 external variable
 External variables are declared out of the main() function.
 The availability of these variables are throughout the program and that
is both in main function and inside the user defined functions.
 An extern variable cannot be initialized it a declaration statement is
written within the block.
 Extern variables have a global scope.
 Extern storage class specifier cannot be used as the parameter
arguments for a function.
Syntax:
extern datatype var1,var2…………..var n;
Example:
extern int a;
// example program
#include<stdio.h>
extern int a=100;
void main()
{
printf(“a is %d”,a);
}
Output: A is 100

register
Registers are special storage classes within a computers cpu, instead of
storing in RAM or main memory. The actual arithmetic and logical
operation that comprise a program are carried out within these registers.
Register specifies that the declared object will have automatic
(local) scope. Hence it cannot be used with the global scope.
 A variable declared with register storage class has to be explicitly
initialized, otherwise it will have a global value.
 It is not possible to compute the address of a register variable.
 Register storage is commonly used for loop counters to improve the
performance of a program.

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 20


Syntax:
register datatype var1,var2…………… var n;
Example:
register int a;
//example program using register
#include<stdio.h>
void main()
{
register int a=10;
printf(“%d”,a);
} Output: 10

typedef
 Typedef storage class specifier is used for syntactic convenience only.
 Typedef is used for creating a synonym or an alias for a known type.
 It is used to create a new name for the existing datatype.
Syntax:
typedef existing_datatype new_datatype_name
Example:
typedef int number; //Now instead of int a; can use as number a;

Typedef does not introduce a new type. It only create synonym for the known
type.
//example program using typedef

#include<stdio.h>
void main()
{
typedef int number;
number a=10; // int a=10;
printf(“a is %d”, a); //output a is 10
}
Summary for storage class

Feature Auto Static extern register typedef

Storage Memory Memory memory CPU


register
Default garbage Zero zero garbage Syntactic
value value value Conversion
Lifetime Local Global Local no only

Linkage No Yes Yes No


(Internal) (External)

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 21


Preprocessor

Preprocessor is a program that processes our source program


before compilation.
The preprocessor is another translator that comes and processes the
source code before it is given to the compiler.
It operates under the control of commands known as preprocessor
directives.
They are placed before main() function is source program. The compiler
examines the preprocessor for any processor directives. If there is any
preprocessor directive the appropriate actions are taken and then the
source program is moved for compilation.
The preprocessor operates under the following process directives.
1. File inclusion
2. Macro substitution
3. Conditional inclusion

1. File inclusion
Used to include an external file, which contains functions or some other
macro directives to our source program. So we need not require that
functions and macros in our source program.
Syntax:
#include “filename” #include “add.c”
#include<filename> #include <stdio.h>

2. Macro substitutions
Used to define symbolic constants in the source program
The identifier/string/integer defined is replaced by macro substitution.
Syntax: #define identifier string integer
Three forms of macros:
i. Simple macros
ii. Argumented macros
iii. Nested macros
i) Simple macros
Commonly used to define symbolic constant
#define a 10 //substitutes a with 10 in all occurrences
in the program
#define pi 3.14
ii) Argumented macros
Used to define more complex and more useful form replacement in the
source program.
Example:
#define sq(n) n*n //macro substitution
Main()

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 22


{
S=sq(a); // replaced as s = a*a
}

iii) Nested macros


The macro defines within another macro called as nested macro.
Example:
#define A 5
#define B A+2

3. Conditional inclusion
Used to control the preprocessor with conditional statements.
#define op p
main()
{
#ifdef p printf(“hi”);
#else printf(“hello”);
#endif
}
Some of the preprocessor directives are
S.no Directive Function

1 #include Used to includes a file

2 #define Used to define symbolic constants

3 #ifdef Used to test a macro defition

4 #undef Used to undefines a macro

5 else Used to specify alternative to #ifdef

6 #ifndef Works exactly opposite of #ifdef

7 #line Used to renumbering the source

8 #error Used to display the user defined manage


during compilation of program

9 #new-line Null directive

Y. AROCKIA RAJ, AP / CSE PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY Page 23

You might also like