unit5.docx

32
Unit-5 STRUCTURES AND UNIONS Introduction to Structure Review Thus far, the only aggregate or structured data type we have used was the array. We used arrays to store (model) collections of data of the same type (and a specified size) using a single name. double x[10]; #define ARRAYSIZE 10 double x[ARRAYSIZE]; We learned to reference individual elements of an array using subscripts such as x[1] or x[i]. double x[10]; x [0] [1] [2 ] [3] [4] [5] [6] [7] [8] [9] We say: The contents of x[1] is 2.0 The contents of x[6] is  1.0 (the decimal point would not fit in the picture). Modeling a Collection of Data of Different Types Often, we have a ne ed to create models of related data of diff erent types. For example, if I owned a music store I wanted to write a program for tracking my inventory of rock ‘n roll CDs I might want to know -- The title of the CD (string of characters) 6. 1. ? 2. 4. -1 7. 0. 5. -3

Upload: soundharya03

Post on 14-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 1/32

Unit-5

STRUCTURES AND UNIONS

Introduction to Structure

Review

Thus far, the only aggregate or structured data type we have used was the array.

We used arrays to store (model) collections of data of the same type (and a

specified size) using a single name.

double x[10];

#define ARRAYSIZE 10

double x[ARRAYSIZE];

We learned to reference individual elements of an array using subscripts such as

x[1] or x[i].

double x[10]; x

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

We say:

The contents of x[1] is 2.0

The contents of x[6] is – 1.0 (the decimal point would not fit in the picture).

Modeling a Collection of Data of Different Types

Often, we have a need to create models of related data of different types. For 

example, if I owned a music store I wanted to write a program for tracking my

inventory of rock ‘n roll CDs I might want to know 

-- The title of the CD (string of characters)

6. 1. ?2. 4.-17.0.5.-3

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 2/32

-- The name of the artist (string of characters)

-- The number of CDs on hand (integer)

-- The cost of the CD (double)

Most computer programming languages now provide a way to model such a

collection of data. In C, the feature we need to use is another structured data type

called a struct.

What Is a Structure?

1. A collection of variables that are functionally related to each other.

2. Each variable that is a member of the structure has a specific type.

3. Different members of the structure may have either the same or different types.

Cf. the elements of an array, which must all be of one type.

4. A structure is a derived data type, constructed from two or more objects of one

or more individual types.

5. The entire structure may bear a name.

6. Each member of the structure must [also] have a name.

7. The scope of the name of a structure member is limited to the structure itself and

also to any variable declared to be of the structure's type.

8. THEREFORE, different structures may contain members having the same name;

these may be of the same or of different types.

9. A self-referential structure contains a member which is a pointer to the same

structure type.

10. Declaration of the structure merely defines the new data type; space is NOTreserved in memory as a result of the declaration.

However, declaration of the structure does define how much memory is needed to

store each variable subsequently declared to be of the type of the defined structure.

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 3/32

Definition for Structure

Structure is the collection of variables of different types under a single name for 

 better handling.

Example: You want to store the information about person about his/her name,

citizenship number and salary. You can create this information separately but,

 better approach will be collection of this information under single name because all

these information are related to person.

Structure Definition in C

Keyword struct is used for creating a structure.

Form of Structure Declaration: Alternative 1

(1) Complete definition including assignment of a tag name to the structure.

(2) The tag name is referred to in subsequent declarations of variables of the type

so defined.

(3) Each such declaration MUST include the keyword struct AND the name of the

user-defined structure type AND the variable name(s).

Declaration:-

struct nameOfTheStructure

{

typeOfFirstMember nameOfFirstMember;

typeOfSecondMember nameOfSecondMember;

typeOfThirdMember nameOfThirdMember;

. . .

};

struct nameOfTheStructure variable1,variable2,. . . ;

Additional variable declarations can subsequently be made for this structure type.

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 4/32

Example 1:-

struct student

{

char firstName[20];

long int studentNumber;

short int entranceYear;

char major[6];

};

struct student undergraduateStudent, graduateStudent;

Form of Structure Declaration: Alternative 2

(1) Basic named definition of the structure is effected same as for Alternative 1.

(2) In ADDITION, one or more variables can be declared within the declaration of 

the structure type to be of the defined type.

(3) Other variables may also be declared subsequently to be of the same type of 

this structure, using the keyword struct together with the tag name and the variable

names.

struct nameOfTheStructure

{

typeOfFirstMember nameOfFirstMember;

typeOfSecondMember nameOfSecondMember;

typeOfThirdMember nameOfThirdMember;

. . .

} variable1OfTheStructure, variable2OfTheStructure, . . .;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 5/32

struct nameOfTheStructure variable3OfTheStructure,

variable4OfThisStructureType, . . . ;

Example 2

struct student

{

char firstName[20];

long int studentNumber;

short int entranceYear;

char major[6];} undergraduateStudent, graduateStudent;

struct student specialStudent;

Form of Structure Declaration: Alternative 3

(1) Tag name is not assigned to the structure when the type is declared.

(2) Variables are specified within the structure declaration to be of the defined

structure type.

(3) Because of the absence of a tag name for the structure type, there is no means

available to ever be able to declare any other variables to be of this same type.

struct /* NO NAME ASSIGNED TO THE TYPE */

{

typeOfFirstMember nameOfFirstMember;

typeOfSecondMember nameOfSecondMember;

typeOfThirdMember nameOfThirdMember;

. . .

} variable1OfTheStructure, variable2OfTheStructure, . . .;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 6/32

Example 3

struct

{

char firstName[20];

long int studentNumber;

short int entranceYear;

char major[6];

} undergraduateStudent, graduateStudent, specialStudent;

Form of Structure Declaration: Alternative 4

(1) Complete definition of the structure, including assignment to it of a tag name.

(2) Subsequently, the tag name is used in a typedef declaration to assign a second

name (i.e., an alias) to the structure. The alias can then be used in declaring a

variable the same way as a native C type name is used, that is, without the keyword

struct, i.e., just like int, char, float, etc.

struct nameOfTheStructure

{

typeOfFirstMember nameOfFirstMember;

typeOfSecondMember nameOfSecondMember;

typeOfThirdMember nameOfThirdMember;

. . .

};

typedef struct nameOfTheStructure AliasForTheStructure;

AliasForThisStructureType variable1OfThisStructureType,

variable2OfThisStructureType, . . . ;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 7/32

Example 4

struct student

{

char firstName[20];

long int studentNumber;

short int entranceYear;

char major[6];

} undergraduateStudent, graduateStudent;

typedef struct student StudentType;

StudentType specialStudent;

Form of Structure Declaration: Alternative 5

(1) Complete definition of the structure without assignment of a tag name.

(2) The keyword typedef is used within the declaration of the structure to assign aname (i.e., an alias) to the structure. The structure itself is anonymous, and has

only the alias name. The alias can be used in the same way as a native C type name

is used , that is, without the keyword struct, i.e., just like int, char, float, etc.

typedef struct

{

typeOfFirstMember nameOfFirstMember;

typeOfSecondMember nameOfSecondMember;

typeOfThirdMember nameOfThirdMember;

. . .

} AliasForThisStructureType;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 8/32

AliasForThisStructureType variable1OfThisStructureType,

variable2OfThisStructureType, . . . ;

Example 5

typedef struct

{

char firstName[20];

long int studentNumber;

short int entranceYear;

char major[6];

} StudentType;

StudentType undergraduateStudent, graduateStudent, specialStudent;

Accessing members of a structure

There are two types of operators used for accessing members of a structure.

  Member operator (.)

  Structure pointer operator(->)

Any member of a structure can be accessed as:

structure_variable_name.member_name

Suppose, we want to access salary for variable p2. Then, it can be accessed as:

 p2.salary

Example of structure

Write a C program to add two distances entered by user. Measurement of distance

should be in inch and feet.(Note: 12 inches = 1 foot)

#include <stdio.h>

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 9/32

struct Distance{

int feet;

float inch;

}d1,d2,sum;

int main(){ printf("1st distance\n");

 printf("Enter feet: ");

scanf("%d",&d1.feet); /* input of feet for structure variable d1 */

 printf("Enter inch: ");

scanf("%f",&d1.inch); /* input of inch for structure variable d1 */

 printf("2nd distance\n");

 printf("Enter feet: ");

scanf("%d",&d2.feet); /* input of feet for structure variable d2 */ printf("Enter inch: ");

scanf("%f",&d2.inch); /* input of inch for structure variable d2 */

sum.feet=d1.feet+d2.feet;

sum.inch=d1.inch+d2.inch;

if (sum.inch>12){ //If inch is greater than 12, changing it to feet.

++sum.feet;

sum.inch=sum.inch-12;

}

 printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch);

/* printing sum of distance d1 and d2 */

return 0;

}

Output

1st distance

Enter feet: 12

Enter inch: 7.9

2nd distance

Enter feet: 2

Enter inch: 9.8

Sum of distances= 15'-5.7"

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 10/32

Structures within structures

Structures can be nested within other structures in C programming.

struct complex

{

int imag_value;

float real_value;

};

struct number{

struct complex c1;

int real;

}n1,n2;

Suppose you want to access imag_value for n2 structure variable then, structure

member n1.c1.imag_value is used.

C Programming Structure and Pointer

Pointers can be accessed along with structures. A pointer variable of structure can

 be created as below:

struct name {

member1;

member2;

.

.

};

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 11/32

-------- Inside function -------

struct name *ptr;

Here, the pointer variable of type struct name is created.

Structure's member through pointer can be used in two ways:

  Referencing pointer to another address to access memory

  Using dynamic memory allocation

Consider an example to access structure's member through pointer.

#include <stdio.h>

struct name{

int a;

float b;

};

int main(){

struct name *ptr,p;

 ptr=&p; /* Referencing pointer to memory address of p */

 printf("Enter integer: ");

scanf("%d",&(*ptr).a);

 printf("Enter number: ");scanf("%f",&(*ptr).b);

 printf("Displaying: ");

 printf("%d%f",(*ptr).a,(*ptr).b);

return 0;

}

In this example, the pointer variable of type struct name is referenced to the

address of p. Then, only the structure member through pointer can be accessed.

Structure pointer member can also be accessed using -> operator.

(*ptr).a is same as ptr->a

(*ptr).b is same as ptr->b

Accessing structure member through pointer using dynamic memory allocation

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 12/32

To access structure member using pointers, memory can be allocated dynamically

using malloc() function defined under "stdlib.h" header file.

Syntax to use malloc()

 ptr=(cast-type*)malloc(byte-size)

Example to use structure's member through pointer using malloc() function.

#include <stdio.h>

#include<stdlib.h>

struct name {

int a;

float b;

char c[30];};

int main(){

struct name *ptr;

int i,n;

 printf("Enter n: ");

scanf("%d",&n);

 ptr=(struct name*)malloc(n*sizeof(struct name));

/* Above statement allocates the memory for n structures with pointer ptr pointingto base address */

for(i=0;i<n;++i){

 printf("Enter string, integer and floating number respectively:\n");

scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);

}

 printf("Displaying Infromation:\n");

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

 printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);

return 0;

}

Output

Enter n: 2

Enter string, integer and floating number respectively:

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 13/32

Programming

2

3.2

Enter string, integer and floating number respectively:

Structure6

2.3

Displaying Information

Programming 2 3.20

Structure 6 2.30

C Programming Structure and Function

In C, structure can be passed to functions by two methods:

  Passing by value (passing actual value as argument)

  Passing by reference (passing address of an argument)

Passing structure by value

A structure variable can be passed to the function as an argument as normal

variable. If structure is passed by value, change made in structure variable in

function definition does not reflect in original structure variable in calling function.

Write a C program to create a structure student, containing name and roll. Ask user 

the name and roll of a student in main function. Pass this structure to a function

and display the information in that function.

#include <stdio.h>

struct student{

char name[50];

int roll;

};

void Display(struct student stu);

/* function prototype should be below to the structure declaration otherwise

compiler shows error */

int main(){

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 14/32

struct student s1;

 printf("Enter student's name: ");

scanf("%s",&s1.name);

 printf("Enter roll number:");

scanf("%d",&s1.roll);Display(s1); // passing structure variable s1 as argument

return 0;

}

void Display(struct student stu){

 printf("Output\nName: %s",stu.name);

 printf("\nRoll: %d",stu.roll);

}

Output

Enter student's name: Kevin Amla

Enter roll number: 149

Output

 Name: Kevin Amla

Roll: 149

Passing structure by reference

The address location of structure variable is passed to function while passing it by

reference. If structure is passed by reference, change made in structure variable in

function definition reflects in original structure variable in the calling function.

Write a C program to add two distances(feet-inch system) entered by user. To

solve this program, make a structure. Pass two structure variable (containing

distance in feet and inch) to add function by reference and display the result in

main function without returning it.

#include <stdio.h>

struct distance{

int feet;

float inch;

};

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 15/32

void Add(struct distance d1,struct distance d2, struct distance *d3);

int main()

{

struct distance dist1, dist2, dist3;

 printf("First distance\n"); printf("Enter feet: ");

scanf("%d",&dist1.feet);

 printf("Enter inch: ");

scanf("%f",&dist1.inch);

 printf("Second distance\n");

 printf("Enter feet: ");

scanf("%d",&dist2.feet);

 printf("Enter inch: ");scanf("%f",&dist2.inch);

Add(dist1, dist2, &dist3);

/*passing structure variables dist1 and dist2 by value whereas passing structure

variable dist3 by reference */

 printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);

return 0;

}

void Add(struct distance d1,struct distance d2, struct distance *d3)

{

/* Adding distances d1 and d2 and storing it in d3 */

d3->feet=d1.feet+d2.feet;

d3->inch=d1.inch+d2.inch;

if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet.

*/

d3->inch-=12;

++d3->feet;

}

}

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 16/32

Output

First distance

Enter feet: 12

Enter inch: 6.8

Second distanceEnter feet: 5

Enter inch: 7.5

Sum of distances = 18'-2.3"

Explanation

In this program, structure variables dist1 and dist2 are passed by value (because

value of dist1 and dist2 does not need to be displayed in main function) and dist3 is

 passed by reference ,i.e, address of dist3 (&dist3) is passed as an argument. Thus,the structure pointer variable d3 points to the address of dist3. If any change is

made in d3 variable, effect of it is seed in dist3 variable in main function.

Unions

Unions are quite similar to the structures in C. Union is also a derived type

as structure. Union can be defined in same manner as structures just the keyword

used in defining union in union where keyword used in defining structure

was struct. 

union car{

char name[50];

int price;

};

Union variables can be created in similar manner as structure variable.

union car{

char name[50];

int price;

}c1, c2, *c3;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 17/32

OR 

union car{

char name[50];

int price;

};

-------Inside Function-----------

union car c1, c2, *c3;

In both cases, union variables c1, c2 and union pointer variable c3 of type union

car is created.

Accessing members of an union

The member of unions can be accessed in similar manner as that structure.

Suppose, we you want to access price for union variable c1 in above example, it

can be accessed as c1.price. If you want to access price for union pointer 

variable c3, it can be accessed as (*c3).price or as c3->price.

Difference between union and structure

Though unions are similar to structure in so many ways, the difference between

them is crucial to understand. This can be demonstrated by this example:

#include <stdio.h>

union job { //defining a union

char name[32];

float salary;

int worker_no;

}u;struct job1 {

char name[32];

float salary;

int worker_no;

}s;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 18/32

int main(){

 printf("size of union = %d",sizeof(u));

 printf("\nsize of structure = %d", sizeof(s));

return 0;

}

Output 

size of union = 32

size of structure = 40

There is difference in memory allocation between union and structure as suggested

in above example. The amount of memory required to store a structure variables is

the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for 

largest element of an union.

What difference does it make between structure and union? 

As you know, all members of structure can be accessed at any time. But, only one

member of union can be accessed at a time in case of union and other members

will contain garbage value.

#include <stdio.h>

union job {

char name[32];

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 19/32

float salary;

int worker_no;

}u;

int main(){

 printf("Enter name:\n");scanf("%s",&u.name);

 printf("Enter salary: \n");

scanf("%f",&u.salary);

 printf("Displaying\nName :%s\n",u.name);

 printf("Salary: %.1f",u.salary);

return 0;

}

Output 

Enter name

Hillary

Enter salary

1234.23

Displaying

 Name: f%Bary

Salary: 1234.2

Note: You may get different garbage value of name.

Why this output? 

Initially, Hillary will be stored in u.name and other members of union will contain

garbage value. But when user enters value of salary, 1234.23 will be stored

in u.salary and other members will contain garbage value. Thus in output, salary is

 printed accurately but, name displays some random string.

Passing Union to a Function

Union can be passed in similar manner as structures in C programming.

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 20/32

Programs in Structures

1) C Program to Store Information (name, roll and marks) of a Student Using

Structure

In this program, a structure (student) is created which contains name, roll and

marks as its data member. Then, a structure variable( s ) is created. Then, data

(name, roll and marks) is taken from user and stored in data members of structure

variable s. Finally, the data entered by user is displayed.

C Program to Store Information of Single Variable

#include <stdio.h>

struct student{

char name[50];int roll;

float marks;

};

int main(){

struct student s;

 printf("Enter information of students:\n\n");

 printf("Enter name: ");

scanf("%s",s.name); printf("Enter roll number: ");

scanf("%d",&s.roll);

 printf("Enter marks: ");

scanf("%f",&s.marks);

 printf("\nDisplaying Information\n");

 printf("Name: %s\n",s.name);

 printf("Roll: %d\n",s.roll);

 printf("Marks: %.2f\n",s.marks);return 0;

}

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 21/32

Output 

2) C Program to Store Information of 10 Students Using Structure

In this program, a structure (student) is created which contains name, roll and

marks as its data member. Then, an array of structure of 10 elements is created.

Then, data (name, roll and marks) for 10 elements is asked to user and stored in

array of structure. Finally, the data entered by user is displayed.

Source Code to Store Information of 10 students Using Structure

#include <stdio.h>

struct student{

char name[50];

int roll;

float marks;

};

int main(){struct student s[10];

int i;

 printf("Enter information of students:\n");

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

{

s[i].roll=i+1;

 printf("\nFor roll number %d\n",s[i].roll);

 printf("Enter name: ");scanf("%s",s[i].name);

 printf("Enter marks: ");

scanf("%f",&s[i].marks);

 printf("\n");

}

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 22/32

printf("Displaying information of students:\n\n");

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

{

 printf("\nInformation for roll number %d:\n",i+1);

 printf("Name: "); puts(s[i].name);

 printf("Marks: %.1f",s[i].marks);

}

return 0;

}

Output 

Enter information of students:

For roll number 1

Enter name: Tom

Enter marks: 98

For roll number 2

Enter name: Jerry

Enter marks: 89

.

.

.

Displaying information of students:

Information for roll number 1:

 Name: Tom

Marks: 98

.

.

.

3) C Program to Store Information Using Structures for n Elements Dynamically

This program asks user to store the value of n and allocates the memory for 

the n structure variable dynamically using malloc() function.

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 23/32

Source Code Demonstrate the Dynamic Memory Allocation for Structure

#include <stdio.h>

#include<stdlib.h>

struct name {

int a;char c[30];

};

int main(){

struct name *ptr;

int i,n;

 printf("Enter n: ");

scanf("%d",&n);

/* Allocates the memory for n structures with pointer ptr pointing to the base

address. */

 ptr=(struct name*)malloc(n*sizeof(struct name));

for(i=0;i<n;++i){

 printf("Enter string and integer respectively:\n");

scanf("%s%d",&(ptr+i)->c, &(ptr+i)->a);

}

 printf("Displaying Infromation:\n");

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

 printf("%s\t%d\t\n",(ptr+i)->c,(ptr+i)->a);

return 0;

}

Output 

Enter n: 2

Enter string and integer respectively:

Programming

22

Enter string, integer and floating number respectively:

Structure

33

Displaying Information:

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 24/32

Programming 22

Structure 33

4) C Program to Add Two Complex Numbers by Passing Structure to a Function

This program takes two distances in inch-feet system and stores in datamembers of two structure variables. Then, this program calculates the sum of two

distances by passing it to a function and result is displayed in main() function.

Source Code to Add Two Complex Number 

#include <stdio.h>

typedef struct complex{

float real;

float imag;}complex;

complex add(complex n1,complex n2);

int main(){

complex n1,n2,temp;

 printf("For 1st complex number \n");

 printf("Enter real and imaginary respectively:\n");

scanf("%f%f",&n1.real,&n1.imag);

 printf("\nFor 2nd complex number \n");

 printf("Enter real and imaginary respectively:\n");

scanf("%f%f",&n2.real,&n2.imag);

temp=add(n1,n2);

 printf("Sum=%.1f+%.1fi",temp.real,temp.imag);

return 0;

}

complex add(complex n1,complex n2){

complex temp;

temp.real=n1.real+n2.real;

temp.imag=n1.imag+n2.imag;

return(temp);

}

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 25/32

Output 

In this program structures n1 and n2 are passed as an argument of function add().

This function computes the sum and returns the structure variable temp to the

main() function.

C Programming Preprocessor and Macros

Preprocessor extends the power of C programming language. Line that begin

with # are called preprocessing directives.

Use of #include

Let us consider very common preprocessing directive as below:

#include <stdio.h>

Here, "stdio.h" is a header file and the preprocessor replace the above line with the

contents of header file.

Use of #definePreprocessing directive #define has two forms. The first form is:

#define identifier token_string

token_string part is optional but, are used almost every time in program.

Example of #define

#define c 299792458 /*speed of light in m/s */

The token string in above line 2299792458 is replaced in every occurrence of 

symbolic constant c.

C Program to find area of a circle. [Area of circle=πr2]

 

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 26/32

#include <stdio.h>

#define PI 3.1415

int main(){

int radius;

float area; printf("Enter the radius: ");

scanf("%d",&radius);

area=PI*radius*radius;

 printf("Area=%.2f",area);

return 0;

}

Output 

Enter the radius: 3

Area=28.27

Syntactic Sugar

Syntactic sugar is the alteration of programming syntax according to the will

of programmer. For example:

#define LT <

Every time the program encounters LT, it will be replaced by <.

Second form of preprocessing directive with #define is:

Macros with argument

Preprocessing directive #define can be used to write macro definitions with

 parameters as well in the form below:

#define identifier(identifier 1,.....identifier n) token_string

Again, the token string is optional but, are used in almost every case. Let us

consider an example of macro definition with argument.

#define area(r) (3.1415*r*r)

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 27/32

Here, the argument passed is r. Every time the program

encounters area(argument), it will be replace by (3.1415*argument*argument).

Suppose, we passed (r1+5) as argument then, it expands as below:

area(r1+5) expands to (3.1415*(r1+5)(r1+5))

C Program to find area of a circle, passing arguments to macros. [Area of 

circle=πr2] 

#include <stdio.h>

#define PI 3.1415

#define area(r) (PI*r*r)

int main(){

int radius;float area;

 printf("Enter the radius: ");

scanf("%d",&radius);

area=area(radius);

 printf("Area=%.2f",area);

return 0;

}

Predefined Macros in C language

Predefined

MacroValue

 __DATE__ String containing the current date

 __FILE__ String containing the file name

 __LINE__ Integer representing the current line number 

 __STDC__ If follows ANSI standard C, then value is a

nonzero integer 

 __TIME__ String containing the current date.

How to use predefined Macros?

C Program to find the current time 

#include <stdio.h>

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 28/32

int main(){

 printf("Current time: %s",__TIME__); //calculate the current time

}

Output Current time: 19:54:39

Storage Class

A storage class defines the scope (visibility) and life time of variables and/or 

functions within a C Program.

There are following storage classes which can be used in a C Program

  auto

  register 

  static  extern

auto - Storage Class

auto is the default storage class for all local variables.

{

int Count;

auto int Month;

}

The example above defines two variables with the same storage class. auto canonly be used within functions, i.e. local variables.

register - Storage Class

register is used to define local variables that should be stored in a register 

instead of RAM. This means that the variable has a maximum size equal to the

register size (usually one word) and can’t have the unary '&' operator applied to it

(as it does not have a memory location).

{register int Miles;

}

Register should only be used for variables that require quick access - such as

counters. It should also be noted that defining 'register' goes not mean that the

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 29/32

variable will be stored in a register. It means that it MIGHT be stored in a register -

depending on hardware and implementation restrictions.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

static int Count;

int Road;

{

 printf("%d\n", Road);

}

static variables can be 'seen' within all functions in this source file. At link time,the static variables defined here will not be seen by the object modules that are

 brought in.

static can also be defined within a function. If this is done the variable is initialized

at run time but is not reinitialized when the function is called. This inside a

function static variable retains its value during various calls.

void func(void);

static count=10; /* Global variable - static is the default */

main()

{

while (count--)

{

func();

}

}

void func( void )

{

static i = 5;

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 30/32

i++;

 printf("i is %d and count is %d\n", i, count);

}

This will produce following result

i is 6 and count is 9

i is 7 and count is 8

i is 8 and count is 7

i is 9 and count is 6

i is 10 and count is 5

i is 11 and count is 4

i is 12 and count is 3i is 13 and count is 2

i is 14 and count is 1

i is 15 and count is 0

NOTE : Here keyword void means function does not return anything and it does

not take any parameter. You can memories void as nothing. static variables are

initialized to 0 automatically.

Definition vs Declaration: Before proceeding, let us understand the difference

 between definition and declaration of a variable or function. Definition means

where a variable or function is defined in reality and actual memory is allocated for 

variable or function. Declaration means just giving a reference of a variable and

function. Through declaration we assure to the complier that this variable or 

function has been defined somewhere else in the program and will be provided at

the time of linking. In the above examples char *func(void) has been put at the top

which is a declaration of this function where as this function has been defined

 below to main() function.

There is one more very important use for 'static'. Consider this bit of code.

char *func(void);

main()

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 31/32

{

char *Text1;

Text1 = func();

}

char *func(void)

{

char Text2[10]="martin";

return(Text2);

}

 Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2

has a storage class of 'auto' and will disappear when we exit the function and could

 be overwritten but something else. The answer is to specify

static char Text[10]="martin";

The storage assigned to 'text2' will remain reserved for the duration if the program.

extern - Storage Class

extern is used to give a reference of a global variable that is visible to ALL

the program files. When you use 'extern' the variable cannot be initialized as all it

does is point the variable name at a storage location that has been previously

defined.When you have multiple files and you define a global variable or function which

will be used in other files also, then extern will be used in another file to give

reference of defined variable or function. Just for understanding extern is used to

declare a global variable or function in other files.

File 1: main.c

int count=5;

main(){

write_extern();

}

File 2: write.c

void write_extern(void);

7/27/2019 Unit5.docx

http://slidepdf.com/reader/full/unit5docx 32/32

 

extern int count;

void write_extern(void)

{

 printf("count is %i\n", count);

}

Here extern keyword is being used to declare count in another file.

 Now compile these two files as follows

gcc main.c write.c -o write

This fill produce write program which can be executed to produce result.

Count in 'main.c' will have a value of 5. If main.c changes the value of count -

write.c will see the new value