Unit - 5 Notes
Unit - 5 Notes
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.
Introduction:
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.
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
struct book
{
char name[20];
float price;
int pages;
}focp ={“c++”,240.75,300};
struct book
{
char name[20];
float price;
int pages;
};
void main()
{
struct focp ={“c++”,240.75,300};
}
Note: focp is the structure varaible that is used to access the members of the structure.
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.
Syntax
Example
This is how the memory will be allocated for the structure variables.
30 bytes
book1
name[20]
20 bytes
price
4 bytes
pages
2 bytes
The members of the structure can accessed using structure variable with a dot(.) operator.
Example
focp.pages;
focp.name;
struct book
{
char name[20];
float price;
int pages;
}focp;
// 'focp' is name of Structure variable
struct book
{
char name[20];
float price;
int pages;
}focp;
struct book focp;
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.
There are two types of operators used for accessing members of a structure.
Member operator(.)
Structure pointer operator(->)
Example
focp.pages;
focp.name;
focp.price;
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);
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;
};
book 30 bytes
name[20]
20 bytes
8 bytes
price price
8 bytes priceInRupees
4bytes
pages priceInDollars
4 bytes
2 bytes
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()
{
struct focp[0] ={“Advanced c”,240.75,300};
struct focp[1] ={“c”,290.75,270};
struct focp[2] ={“basic C”,300.00,380};
}
Example Program
#include<stdio.h>
#include<conio.h>
struct Employee
{
int ssn;
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].ssn,emp[i].ename,emp[i].dept);
}
//Print Employee Details
for(i=0;i<3;i++)
{
printf("nEmployee SSN : %d",emp[i].ssn);
printf("nEmployee Name : %d",emp[i].ename);
printf("nEmployee Dept : %d",emp[i].dept);
}
getch();
}
Output :
Enter the Employee Details : 1 Ram Testing
Employee SSN : 1
Employee Name : Ram
Employee Dept : Testing
#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 to 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.
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.
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
Structure Union
i. Access Members
Memory is allocated for each and every Allocates memory for variable which variable require the
variable i.e. the memory allocated will be largest memory i.e. the memory allocated will be equal to
equal to the sum memory required for every the 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
vi. Example
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.2.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 code.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
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
5.2.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 definition
1. Simple Macro
2. Macro with argument.
Simple Macro
Syntax for #define
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();
}
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
Note: A macro definition should never end with a semicolon. A macro definition in capitals is a
convention not a rule.
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
will 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
Syntax
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:
Explanation:
Note: Macro are closely related to function concepts, but it is not a substitute for function.
Predefined
Value
macro
__DATE__ String containing the current date
#include <stdio.h>
void main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}
Output
No Macro Function
1 Macro is Preprocessed Function is Compiled
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
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
File inclusive Directories are used to include user define header file inside C Program.
File inclusive directives begins with #include
.
Syntax
It cause the entire content of the given filename to be include in the program, before the execution begins.
#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
Step 1 : First create a file Arithmetic.h which contains the following code:
Output:
Sum = 15
Subtraction = 5
Multiplication = 50
Division = 2
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 ,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
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.
#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:
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.
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.
(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
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
#pragma startup: It allows a function to be called before the main program (i.e before the program execution).
#pragma exit: It allows a function to be called after the main program (i.e at the end of the program
termination).
Syntax: startup pragma
startup pragma allow the program to specify function(s) that should be called upon program startup
exit pragma allow the program to specify function(s) that should be called just before the program
terminates through _exit.
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