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.
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.
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.
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
The values will be assigned in the order that they are declared.
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.
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.
Syntax
Example
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;
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.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);
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
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
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}
};
#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 used to create data structures like linked lists, stacks, etc.
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.
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;
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
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
vi. Example
#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 );
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 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);
return 0;
}
Output :
data.i = 12
data.f = 200.000000
data.str = Let Us C
1. auto
2. register
3. static
4. extern
Computer memory is any physical device capable of storing information temporarily or permanently.
1. Primary
2. Secondary.
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.
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. { }.
Program: In c language a life of a variable may be within a program (one or more files).
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.
For example:
#include<stdio.h>
void main()
int i;
auto char c;
float f;
printf("%d %c %f",i,c,f);
(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.
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.
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()
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
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.
For example:
#include <stdio.h>
static char c;
static int i;
static float f;
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++)
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 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.
File scope: visible from the point of the declaration to the end of the file.
Example:
#include <stdio.h>
#include <stdlib.h>
void display();
void main()
int mum ;
printf("nNum : %d",num);
display();
}
void display()
int mum ;
printf("nNum : %d",num);
Output
Num : 75
Num : 75
Local to the
block in Till the program
<static> <datatype>
Static Memory. Zero. which the Execution
variable Example:
terminates
is defined. static int i ;
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.
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
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.
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
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();
}
#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 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
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
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:
Note: Macros are closely related to functions, but it is not a substitute for function.
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.
#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 causes the entire content of the given filename to be included 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
Step 1 : First create a file Arithmetic.h 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
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
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.
#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 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).
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