[go: up one dir, main page]

0% found this document useful (0 votes)
18 views43 pages

Unit - 5 Notes

The document provides an overview of structures and unions in programming, explaining their definitions, declarations, initialization, and access methods. It highlights the differences between structures and unions, particularly in memory allocation and member access. Additionally, it includes examples of how to use structures and unions in programs, along with a brief discussion on storage classes in C.

Uploaded by

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

Unit - 5 Notes

The document provides an overview of structures and unions in programming, explaining their definitions, declarations, initialization, and access methods. It highlights the differences between structures and unions, particularly in memory allocation and member access. Additionally, it includes examples of how to use structures and unions in programs, along with a brief discussion on storage classes in C.

Uploaded by

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

UNIT V

STRUCTURES AND UNIONS

Syllabus:

Introduction – Need for structure data type – Structure definition - Structure Declaration – Structure within a
structure - Unions – Programs using structure and union – Storage classes – The Preprocessor Directives.

5. STRUCTURES AND UNIONS

5.1 Introduction to Structures and Unions

Structure Definition
Structure is defined as collection of different data types.
Structure is a method of packing data of different types. It collects different data type values under single
variable name.
 As we know that Array is collection of the elements of similar type, but many time we will need to
store the elements of different data types.
 Collection of different data type items it is not possible using an array.
 When we require using a collection of different data items of different data types we can use a
Structure.
Array is a homogeneous collection of data whereas Structure and Union are heterogeneous collection of data.
Union is also as collection elements of different data type, but the difference between the structure and union
lies in the way the compiler allocates the memory.

5.1.1 Need for Structure

In most of the cases, we need to store information that is related to each other. But the information may not be
of same type.

Consider an example where we have to store the details of book. (pages, name, price)

Here the name should be stored as character array, the pages should be stored as integer, and the price should be
stored as float.

We cannot do this with an array, since array is a collection of similar data types.

5.1.2 Structure Declaration


Syntax
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Example

struct book
{
char name[20];
float price;
int pages;
};
Note :
Each variable declared in Structure is called member.
The members in the above structure are
char name[20];
float price;
int pages;
Name given to structure is called as tag
Example: book

5.1.3 Structure Initialization

A structure can be initialized as follows

struct focp ={“c++”,240.75,300};

The values will be assigned in the order that they are declared.

A structure can be initialized at the end of the structure like


struct book
{
char name[20];
float price;
int pages;
}focp ={“c++”,240.75,300};

or it can be initiialized in the main function as follows

struct book
{
char name[20];
float price;
int pages;
};

void main()
{
book focp ={“c++”,240.75,300};
}

Note: focp is the structure varaible that is used to access the members of the structure.

Rules for structure initialization

 The order of data type of the structure members in the declaration, should match with the order in the
initialization.
 Individual structure members cannot be initialized separately
 The uninitialized structure members will be assigned default values(0 for int and float and ‘\0’ for
character)
5.1.4 Accessing the Elements of the Structure

Whenever a structure is created, we should also create a Structure Variable to access the elements of structure.

The memory is allocated for the structure, only when the Structure Variable is created.

A structure can have any number of Structure Variable.


Each Structure Variable will have its own copy of the elements of the structure.

Declarating Structure Variable

Syntax

struct StructureName StructureVariablesName;

Example

struct book focp;

This is how the memory will be allocated for the structure variables.

30 bytes

The members of the structure can accessed using structure variable with a dot(.) operator.

Example

focp.pages;

focp.name;

Different Ways of Declaring Structure Variable

Method 1: Immediately after Structure Template

struct book
{
char name[20];
float price;
int pages;
}focp;
// 'focp' is name of Structure variable

Inside the main function

struct book
{
char name[20];
float price;
int pages;
}focp;
struct book focp;

Declaring Multiple Structure Variables

struct book
{
char name[20];
float price;
int pages;
}focp1,focp2,focp3;
We can declare multiple variables separated by comma directly after closing curly braces.

Accessing members of a structure

There are two types of operators used for accessing members of a structure.
 Member operator (.)
 Structure pointer operator(à)
Example
focp.name;

focp.price;

focp.pages;

Example Program
#include<stdio.h>
struct book
{
char name[20];
float price;
int pages;
}focp1;
void main()
{
printf(“Enter The Book Name = ”);
scanf(“%s”,focp1.name);
printf(“Enter The Book Price = ”);
scanf(“%f”,&focp1.price);
printf(“Enter The Book Pages = ”);
scanf(“%d”,&focp1.pages);

printf(“Book Name = %s”,focp1.name);


printf(“Book Price = %f”,focp1.price);
printf(“Book Pages = %d”,focp1.pages);
}
Note : Dot operator has Highest Priority than unary, arithmetic, relational and logical Operators

5.1.5 Structure within Structure

A structure within a structure is called as nested structure. It is also called as embedded structure.

Example

struct book
{
char name[20];
struct price
{
float priceInRupees;
float priceInDollars;
};
int pages;
};
30
bytes

8
bytes

5.1.6 Arrays of Structure

An array of structure variable is called as array of structures.

For Example, in the structure book if we create an array of structure variables as follows

struct book
{
char name[20];
float price;
int pages;
}focp[3];

void main()
{
book focp[0] ={“Advanced c”,240.75,300};
book focp[1] ={“c”,290.75,270};
book focp[2] ={“basic C”,300.00,380};
}
Example Program
#include<stdio.h>
#include<conio.h>

struct Employee
{
int eid;
char ename[20];
char dept[20];
}emp[3]; //array of structure
void main()
{
int i,sum;
for(i=0;i<3;i++)
{
printf("\nEnter the Employee Details : ");
scanf("%d %s %s",&emp[i].eid,emp[i].ename,emp[i].dept);
}
//Print Employee Details
for(i=0;i<3;i++)
{
printf("nEmployee ID : %d",emp[i].eid);
printf("nEmployee Name : %d",emp[i].ename);
printf("nEmployee Dept : %d",emp[i].dept);
}
getch();
}
Output :
Enter the Employee Details : 1 Ram Testing
Employee ID : 1
Employee Name : Ram
Employee Dept : Testing

Initializing Array of Structure

struct book
{
char bname[20];
int pages;
char author[20];
float price;
}b[3] = {
{"Let us C",700,"YPK",300.00},
{"Wings of Fire",500,"APJ Abdul Kalam",350.00},
{"Complete C",1200,"Herbt Schildt",450.00}
};

5.1.7 Passing Array of Structure

 Array of Structure can be passed to function as a Parameter.


 Function can also return Structure as return type.
Example

#include<stdio.h>
#include<conio.h>
struct Example
{
int num1;
int num2;
}s[3];
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
void main()
{
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
5.1.8 Self Referential Structure

A self-referential structure is a structure which refers itself.

A self referential structure is used to create data structures like linked lists, stacks, etc.

Following is an example of this kind of structure:


Syntax
struct struct_name
{
datatype datatypename;
struct struct_name * pointer_name;
};

Example
struct LinkedList
{
int data;
struct LinkedList *address;
};
Here the structure LinkedList contains a varaible *address which is its own structure data type LinkedList
Calculate Size of Structure
Structure is used for collecting different data types together. There are different ways of calculating size of
structure by Using sizeof Operator.
Program
#include<stdio.h>
struct book
{
char name[20]; // 20 x1  20 bytes
float price; // 4 bytes
int pages; // 2 bytes
}focp1;
void main()
{
printf(“Size of Structure = %d”,sizeof(focp1));
}
Output
Size of Structure = 26

20 + 4 + 2 =26
Uses / Applications of Structure
1. Implementing linked list, stack etc.

2. Creating the directory structure for a disk

5.1.9 Introduction to Union

Union is similar to the structure. It also contains members like structures, but it does not allocate memory for
every single member, but it allocates the memory only for the variable which requires largest memory.
Union and Structure
union stud struct stud
{ {
int roll; int roll;
char name[4]; char name[4];
int marks; int marks;
}s1; }s1;

Only one Member will be active at a time


Suppose we are accessing one data members of union then it is not possible to access other data members of
that union. This is because each data member shares same memory.
By Using Union we can Save more memory spaces.
Syntax

union unionName
{
union_member1;
union_member2;
union_member3;
..
..
..
union_memberN;
}unionVariable;

Simple Example

union stud
{
int roll;
char name[4];
int marks;
}s1;

Where stud is the union name and s1 is the union variable that can access the members of the union.

Consider the example below to understand the way in which structure and union differs in memory
allocation

#include <stdio.h>
union job
{
char name[32]; // 32 bytes
float salary; // 4 bytes
int worker_no; // 2 bytes
}u;
struct job1
{
char name[32]; // 32 bytes
float salary; // 4 bytes
int worker_no; // 2 bytes
}s;
void main()
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
}
Output
size of union = 32
size of structure = 38
Explanation:

The amount of memory required to store a structure variables is the sum of memory size(32 + 4 + 2 = 38 bytes)
of all members.

But, the memory required to store a union variable is the memory required for largest element(32 bytes) of an
union
5.1.10 Structure Vs Union

Structure Union

i. Access Members

All the members of structure can be accessed


Only one member of union can be accessed at a time.
simultaneously.

ii. Memory Allocation

Memory is allocated for each and every Allocates memory for variable which requires the largest
variable i.e. the memory allocated will be memory i.e. the memory allocated will be equal to the
equal to the sum memory required for every memory required, for the variable which needs largest
variable. memory.

iii. Initialization

Every members of structure can be initialized Only the first member of a union can be initialized.

iv. Keyword

'struct' keyword is used to declare structure. 'union' keyword is used to declare union.

v. Syntax

struct struct_name union union_name


{ {
structure element 1; union element 1;
structure element 2; union element 2;
---------- ----------
---------- ----------
structure element n; union element n;
}struct_var_nm; }union_var_nm;

vi. Example

struct item_mst union item_mst


{ {
int rno; int rno;
char nm[50]; char nm[50];
}it; }it;

5.1.11 Programs using structure and union

Structure Examples Program

#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};

/* function declaration */
void printBook( struct Books book );

int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming Concepts");
strcpy( Book1.author, "James");
strcpy( Book1.subject, "C Tutorial");
Book1.book_id = 642124;

/* book 2 specification */
strcpy( Book2.title, "Let Us C");
strcpy( Book2.author, "Kanetkar");
strcpy( Book2.subject, "C Programming");
Book2.book_id = 642123;
/* print Book1 info */
printBook( Book1 );

/* Print Book2 info */


printBook( Book2 );
}

void printBook( struct Books book )


{
printf( "Book Title = %s\n", book.title);
printf( "Book author = %s\n", book.author);
printf( "Book Subject = %s\n", book.subject);
printf( "Book Book_ID = %d\n", book.book_id);
}

Output:
Book Title = C Programming Concepts
Book Author = James
Book Subject = C Tutorial
Book Book_ID = 642124
Book Title = Let Us C
Book Author = Kanetkar
Book Subject = C Programming
Book Book_ID : 642123

Union Example Program


#include <stdio.h>
#include <string.h>

union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;

data.i = 12;
printf( "data.i = %d\n", data.i);

data.f = 220.5;
printf( "data.f = %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str = %s\n", data.str);

return 0;
}

Output :
data.i = 12
data.f = 200.000000
data.str = Let Us C

5.2 Storage Classes

In C there are four types of storage class. They are:

1. auto

2. register

3. static

4. extern

Storage class is modifier or qualifier of data types which decides:

1. In which area of memory a particular variable will be stored?

2. What is life of variable?

3. What is scope of variable?


4. What will be the initial value of the variable, if initial value is not explicitly assigned?

In which area of memory a particular variable will be stored?

 Computer memory is any physical device capable of storing information temporarily or permanently.

 Memory can be categorized as

1. Primary

2. Secondary.

 Whenever we refer to memory here it means Primary memory.

In C, by default the values are stored in Main Memory.

What is life of variable?

 Life of a variable defines whether a variable is alive or dead. Alive means the data of a variable
has not destroyed from memory and dead means it has been destroyed form the memory.

 The part or area of the program up to which a variable is alive, is known as scope of a variable.

A life of an variable may be within a

1. Block.

2. Function.

3. File.

4. Program.
Block: In C, block is represented as an area between opening curly bracket and closing curly bracket i.e. { }.

Function: A block of user-defined function is called as function block.

File: In c language a life of a variable may be within a file.

Program: In c language a life of a variable may be within a program (one or more files).

what is the scope of a variable:

Scope means accessibility. It defines up to which part or area of a program a variable can be accessed.

For example:

void main()

int a;
Scope of variable
............... ‘a’ is within this
block
................

What will be the initial value of the variable, if initial value is not explicitly assigned?

In c when a variable is not initialized a value, some random variable called as default value will be assigned to
it. Mostly the default value will be either zero or garbage value.
auto - Storage Class

Automatic variables or auto variables are default storage class of local variable.

(1) Default initial value of auto variable is garbage.

For example:

#include<stdio.h>

void main()

int i;

auto char c;

float f;

printf("%d %c %f",i,c,f);

Output: Garbage Garbage Garbage

(2) Scope of auto variable is within the block where it has declared. For examples:

#include<stdio.h>

void main()

int a=10;

int a=20;

printf("%d",a);

printf(" %d",a);
}

Output: 20 10

Explanation: scope of variable a which has been declared inside inner block has scope only within that block.

(3) Life of auto variable is within the block where it has declared. For example:

#include<stdio.h>

void main()

int i;

for(i=0;i<4;i++)

int a=20;

printf("%d",a);

a++;

Output :

20 20 20 20

Explanation: Variable declared inside the for loop has scope only within that block. After the first iteration
variable a becomes dead and it looses its incremented value. In second iteration variable a is again initialized.

register – Storage Class

A register storage class is very similar to an auto storage class in all aspects except for the fact that the register
variables in c are stored in CPU register and not in the memory.

Important points about register storage class


(1) In following declaration:

register int a;

We are only requesting not forcing to compiler to store variable a in CPU Register. Compiler will decide where
to store the variable a in CPU Register or not.

(2) A register variable execute faster than other variables because it is stored in CPU Register so during the
execution compiler has no extra burden to bring the variable from main memory to CPU.

(3) Since a CPU will have limited number of register, it is responsibility of a programmer to decide which
variable should be declared as register variable. It will be ideal to declare most frequently used variable as a
register variable.

(4) We cannot dereference register variable since it has not any memory address. For example:

#include<stdio.h>

void main()

register int a,b;

scanf("%d%d",&a,&b);

printf("%d %d",a,b);

Output: Compilation error

(5) Default initial value of register variable is garbage.

(6) Scope and visibility of register variable is block.

static – Storage Class

Static keyword is used for declaring static variables in c. This modifier can be used with all data types like int,
float, double, array, pointer, structure, function etc.

Important points about static keyword:

(1) It is not default storage class of global variables.


(2) Default initial value of static integral type variables are either zero or null.

For example:

#include <stdio.h>

static char c;

static int i;

static float f;

static char *str;

void main()

printf("%d %d %f %s",c,i,f,str);

Output:

0 0 0.000000 (null)

(3) A same static variable can be declared many times but it will be initialize only one time. For example:

#include<stdio.h>

void main()

int i;

for(i=0;i<5;i++)

static int i=20;

printf("%d",i++);

Output:

20 21 22 23 24
In the above program though the statement static int i=20 is executed five times, it is initialized only once.

Note: Assigning any value to the variable at the time of declaration is known as initialization while
assigning any value to variable not at the time of declaration is known assignment.

extern – Storage Class

 extern keyword is used to create global variable which is visible to all program files.

 extern keyword is used to declare a global variable which can be accessed across files.

 The extern modifier is most commonly used when two or more files share the same global variables.

 Any global variable is an external variable.

 External variable: declared outside the body of a function

 File scope: visible from the point of the declaration to the end of the file.

 Static storage duration: through the duration of the program.

 External/global variables have file scope and static storage duration.

Example:

#include <stdio.h>

#include <stdlib.h>

extern int num = 75 ;

void display();

void main()

int mum ;

printf("nNum : %d",num);

display();

}
void display()

int mum ;

printf("nNum : %d",num);

Output

Num : 75

Num : 75

Summary of Storage Class


Storage
Default Initial
Class Storage Scope Life Syntax
Value

Till the program


Execution
Local to the
remains within
Any random <auto> <datatype>
block in
the block
value ,called
Auto Memory. which the Example:
the garbage in which the
variable
value variable is auto int i;
is defined.
defined.

Till the program


Execution
Local to the
remains within
Any random <register> <datatype>
block in
the block
CPU value ,called
Register which the Example:
registers the garbage in which the
variable
value variable is register int i ;
is defined.
defined.

Local to the
block in Till the program
<static> <datatype>
Static Memory. Zero. which the Execution
variable Example:
terminates
is defined. static int i ;

The scope is Till the program <extern> <datatype>


Extern Memory. Zero. throughout Execution Example:
the program terminates extern int i ;

5.3 The Preprocessor

 Is it possible to write C program that calls an user defined function before main() function?
 Can we have two main() function in same program?
Yes..... it is possible with the help of using Preprocessor

5.3.1 Introduction

 Pre processor is a program that processes our source program before compilation.
 Preprocessor directives are initialized at the beginning of the program before the main().
 Preprocessor always begins with # (hash) and does not require any semicolon at the end.
All the preprocessor process before the starting of actual compilation and create an intermediate file. In the
intermediate file all preprocessor statement is replaced by corresponding C codes. During the compilation
process that intermediate file is deleted by compiler automatically.

 A set of commonly used preprocessor directives


Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file
#undef Undefines a preprocessor macro
#ifdef Returns true if the macro is defined
#ifndef Returns true if the macro is not defined
#if Tests whether a compile time condition is true
#else The alternative for #if
#elif #else an #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr
Issues special commands to the compiler, using
#pragma
a standardized method

Note : Program that Processes or Analyzes the source code file before Given to the Compiler is called as Pre-
Processor.
The preprocessor directives can be divided into four categories:
(a) Macro Expansion

(b) File Inclusion Directive or #include Directive

(c) Conditional Compilation

(d) Miscellaneous directives

5.3.2 Advantages of Preprocessor

The advantage of using macro is the execution speed of the program fragment. When the actual code snippet is
to be used, it can be substituted by the name of the macro. The same block of statements, on the other hand,
need to be repeatedly hard coded as and when required.

A macro is a name given to a block of the code which can be substituted where the code snippet is to be used
for more than once.

- The speed of the execution of the program is the major advantage of using a macro.

- It saves a lot of time that is spent by the compiler for invoking / calling the functions.

- It reduces the length of the program.

5.3.3 Macro Expansion

5.3.3.1 Introduction

 Macro Expansion is a process where an identifier in a program is replaced by a string composed of one
or more tokens.
 The #define statement is used for macro expansion.
 Preprocessor replaces every occurrence of the identifier in the source code by that string.
 There are 2 types of macro definitions,
1. Simple Macro
2. Macro with argument.

Simple Macro
Syntax for #define

#define Macro_Template Macro_Expansion

Example

#define PI 3.14

Example program 1
Source Code before Processing by compiler:
#include<stdio.h>
#include<conio.h>
#define MAX 9
void main()
{
int i = MAX;
printf("Age of Child : %d",MAX);
getch();
}

Final Source Code after Processing by compiler:


void main()
{
int i = 9;
printf("Age of Child : %d",9);
getch();
}
Example Program 2

#include<stdio.h>
#define LIMIT 5
void main( )
{
int i ;
for ( i = 1 ; i <= LIMIT; i++ )
printf ( "\t %d", i ) ;
}

Output

1 2 3 4 5

Explanation

In the above program instead of using i<=5,we are writing as i<=LIMIT and defining LIMIT as 5. Here the
macro replaces every occurrence of limit as 5.

Example Program 3

#include <stdio.h>
#define PI 3.1415
void main()
{
int radius;
float area;
printf("Enter the radius: ");
scanf("%d",&radius);
area=PI*radius*radius;
printf("Area=%.2f",area);
}

Output

Enter the radius: 3


Area=28.27
Explanation

In the above program the identifier PI is replaced by the value 3.1415

Note: A macro definition should never end with a semicolon. A macro definition in capitals is a
convention not a rule.

How C Preprocessor Works

5.3.3.2 Advantages of Macro

1. Readability: Consider that we are going to use the value of PI (3.141592) in a program. Then we can define
that using macro as

# define PI 3.141592

Because it will be more meaningful to use the value as PI rather than as 3.141592.

When someone other than the programmer reads the program, he/she can understand that PI is 3.141592 but it
would be difficult for him/her to assume that 3.141592 as PI

2. Flexibility : If we have uses the value of PI, a hundred times in a program and at some instance we need to
change the value of PI from 3.141592 to 3.14 ,then we need not replace all the occurrence but only one
occurrence, i.e., we can redefine the macro as

# define PI 3.14

5.3.3.3 Macro with Arguments

The macros that we have used so far are called simple macros. Macros can have arguments. Preprocessor
permits us to define more complex and more useful form of macros.

Syntax

#define Identifier(f1,f2,f3…..fn) String

Example

#define square(x) ( x * x )

Example Program 1

#include<stdio.h>
#define SQUARE(x) ( x * x )
void main( )
{
printf ( "Square of 3 = %d", SQUARE(3) ) ;
}
Output

Square of 3 = 9

Explanation

SQUARE(3) is expanded as (3 * 3 )

Example Program 2

#include <stdio.h>
#define PI 3.1415
#define area(r) (PI*r*r)
void main()
{
int radius;
float area;
printf("Enter the radius: ");
scanf("%d",&radius);
area=area(radius);
printf("Area=%.2f",area);
}
Output:

Enter the radius:12


Area= 452.38
Explanation:

area(radius) is expanded as 3.1415*12*12

Note: Macros are closely related to functions, but it is not a substitute for function.

5.3.3.4 Predefined Macros in C language

Predefined
Value
macro
__DATE__ String containing the current date
__FILE__ String containing the file name
__LINE__ Integer representing the current line number
If follows ANSI standard C, then value is a nonzero
__STDC__
integer
__TIME__ String containing the current time.

Example of using predefined Macros

C Program to find the current time:

#include <stdio.h>
void main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}
Output

Current time: 19:54:39

5.3.2.5 Difference Between Macro and Function

No Macro Function
1 Macro is Preprocessed Function is Compiled

2 No Type Checking Type Checking is Done

3 Code Length Increases Code Length remains Same

4 Use of macro can lead No side Effect


to side effect

5 Speed of Execution is Speed of Execution is Slower


Faster

6 Before Compilation macro name is replaced During function call , Transfer of Control
by macro value takes place

7 Useful where small code appears many time Useful where large code appears many time

8 Generally Macros do not extend beyond one Function can be of any length
line

9 Macro does not Check Compile Errors Function Checks Compile Errors

Example Program 4

#define CUBE(x) (x*x*x)


void main()
{
int volume =CUBE(3+2);
printf("%d",volume);
}
What will be the output?
Actually the output is expected to be 125 but it is wrong.
Output
17
Explanation :
This program will be expanded as:

void main()
{
int volume =CUBE(3+2*3+2*3+2);
printf("%d",volume);
}
= 3+2*3+2*3+2
= 3+6+6+2
= 17

5.3.4 File Inclusion Directive or #include Directive

 File inclusive Directories are used to include user define header file inside C Program.
 File inclusive directives begins with #include
.
Syntax

#include "filename.h" or #include <filename.h>

It causes the entire content of the given filename to be included in the program, before the execution begins.

There are two possible Ways of including header file

Way 1 : Including Standard Header Files


#include<filename>
 Searches for the included file in Standard Library first.

Way 2 :User Defined Header Files are written in this way

#include "filename"
 Searches for the included file in Current Library first.
 If not found , then it Searches in Standard Library

Example Program

Including Predefined Files


#include <stdio.h> // Standard Header file
#include <conio.h> // Standard Header file
void main()
{
clrscr();
printf(“Welcome”);
getch();
}
Steps To implement Userdefined Files

Step 1 : First create a file Arithmetic.h which contains the following code:

int add (int x, int y)


{
return x+y;
}
int sub (int x, int y)
{
return x-y;
}
int mul(int x, int y)
{
return x*y;
}
int div (int x, int y)
{
return x/y;
}
Step 2 : Now create another c file Math.c which contains the following code

#include <stdio.h>
#include “Arithmetic.h” // User Defined File
void main( )
{
int a=10,b=5,t=0;
t=add(a,b);
printf(“Sum = %d”,t);
t=sub(a,b);
printf(“Subtract = %d”,t);
t=mul(a,b);
printf(“Multiplication = %d”,t);
t=div(a,b);
printf(“Division = %d”,t);
}

Output:

Sum = 15
Subtraction = 5
Multiplication = 50
Division = 2

5.3.5 Conditional Compilation

 Conditional compilation is the processes of making the compiler skip a block of source code by inserting
the preprocessing commands.
 Six directives are available to implement conditional compilation
#if #ifdef #endif #ifndef #else #elif.
 Conditional compilation means compilation based on a condition, the compilation is done.
#If Directive

It is conditional compilation directive. That is if condition is true then it will compile the c programming code
otherwise it will not compile the c code.

Syntax 1

#if <Constant_expression>
-------------
-------------
#endif
If the constant expression returns a value of 0, then the condition will be false and the block of statements
between #if and #endif will be not be executed.

If the constant expression returns a non-zero value, then the condition will be true and the block of statements
between #if and #endif will be executed.

Example 1

#include<stdio.h>
#if 0
void main()
{
printf("Welcome");
}
#endif
Output

Run time error, undefined symbol _main

Explanation: The constant expression is 0 and so #if condition will false. So c code inside the #if condition will
not be executed. Since there is no main function, the compiler generates an error.

Note: The #else is similar to the #if directive, but in the case of #else directive the statements will be executed
only if the condition is false.

Syntax for #if and #else:

#if <Constant_expression>
-----------------
-----------------
#else
-----------------
-----------------
#endif
Example 2a

#include<stdio.h>
#if 5
void main()
{
printf("Condition True");
}
#else
void main()
{
printf("Condition False");
}
#endif
Output:

Condition True

Explanation:

5 is non zero number so #if condition is true.

Example 2b

#include<stdio.h>
#if 0
void main()
{
printf("Condition True");
}
#else
void main()
{
printf("Condition False");
}
#endif
Output:

Condition False

Explanation:

Since the value is 0, #if condition is false and statements in #else is executed.

Note : This C program contains more than one main()


Example 3

#include<stdio.h>
#define var 10
void main()
{
#if var
printf("Welcome To C World");
#else
printf("Thank you! Try Again");
#endif
}
Output:

Welcome To C World.

Explanation:

Macro constant var will be replaced 10. Since 10 is non-zero number so #if part will execute.

5.3.5 Miscellaneous Directive

There are two miscellaneous preprocessor directives and they are

(a) #undef

(b) #pragma

#undef Directive

Directive #undef is used to undefine any macro constants except global identifiers. It is useful when we want to
redefine any macro constants.

Syntax

#undef macro template

Example Program

#include<stdio.h>
#define ABC 25
#ifdef ABC
#undef ABC
#define ABC 50
#else
#define ABC 100
#endif
void main()
{
printf("%d",ABC);
}
Output

50

Explanation

Since macro constant ABC has already defined, #ifdef condition is true and the Directive #undef will undefine
the macro constant ABC. However, the statement #define ABC 50 will again define the macro ABC.
#pragma Directive

It has two types:

1. #pragma startup and


2. #pragma exit

#pragma startup: It allows a function to be called before the execution of main program (i.e., before the
program execution).

#pragma exit: It allows a function to be called after the execution of main program (i.e., at the end of the
program termination).

Syntax: startup pragma

#pragma startup <function_name> [priority]

 startup pragma allow the program to specify function(s) that should be called upon program startup

 Function is called before main() starts execute.

Syntax: exit pragma


#pragma exit <function_name> [priority]

 exit pragma allow the program to specify function(s) that should be called just before the program
terminates through _exit.

 Function is called after main() executes.

Priority
 0 = Highest priority
 0-63 = Used by C libraries
 64 = First available user priority
 100 = Default priority
 255 = Lowest priority
The optional priority parameter is an integer in the range from 64 to 255.
Example:

#include <stdio.h>
void fun1(); //function Declaration
void fun2(); //function Declaration
#pragma startup fun1
#pragma exit fun2
void main( )
{
printf ( "\nI am Inside main" ) ;
}
void fun1( )
{
printf ( "\nI am before main" ) ;
}
void fun2( )
{
printf ( "\nI am after main" ) ;
}
Explanantion

Here the fun1 will be called before the execution and fun2 will be called after the main program.
Output

I am before main

I am inside main

I am after main

You might also like