Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Programming in C-Structures and Unions

STRUCTURES AND UNIONS

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

5.1 INTRODUCTION

DEFINING A STRUCTURE

To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as follows

struct [structure tag] {


member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of the
structure's definition, before the final semicolon, you can specify one or more structure
variables but it is optional. Here is the way you would declare the Book structure –

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

ACCESSING STRUCTURE MEMBERS

To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and the
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

structure member that we wish to access. You would use the keyword struct to define
variables of structure type. The following example shows how to use a structure in a program

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

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

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");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}

When the above code is compiled and executed, it produces the following result

Book 1 title : C Programming


Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Declaration of a Structure:

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

A "structure declaration" names a type and specifies a sequence of variable values (called
"members" or "fields" of the structure) that can have different types. An optional identifier,
called a "tag," gives the name of the structure type and can be used in subsequent references
to the structure type.

5.2 NEED FOR STRUCTURE DATATYPE:

 A structured data type is a compound data type which falls under user-defined
category and used for grouping simple data types or other compound data types.
 This contains a sequence of member variable names along with their type/attributes
and they are enclosed within curl brackets.
 Structure is a user-defined datatype in C language which allows us to combine data of
different types together.
 Structure helps to construct a complex data type which is more meaningful.
 It is similar to an Array, but an array holds data of similar type only.In structure, data
is stored in form of records.
 A structure in C is a collection of items of different types. You can think of a structure
as a "record" is in Pascal or a class in Java without methods.
 Structures, or structs, are very useful in creating data structures larger and more
complex than the ones we have discussed so far.
 Object conepts was derived from Structure concept. You can achieve few object
oriented goals using C structure but it is very complex.

EXAMPLE: HOW TO DEFINE A STRUCTURE?

struct student {
char firstName[20];
char lastName[20];
char SSN[9];
float gpa;
};
A new datatype called student ,can use this datatype define variables of student type: struct
student student_a, student_b; or an array of students as struct student students[50];

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

#include <stdio.h>
struct student {
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
};

main()
{
struct student student_a;

strcpy(student_a.firstName, "Deo");
strcpy(student_a.lastName, "Dum");
strcpy(student_a.SSN, "2333234" );
student_a.gpa = 2009.20;

printf( "First Name: %s\n", student_a.firstName );


printf( "Last Name: %s\n", student_a.lastName );
printf( "SNN : %s\n", student_a.SSN );
printf( "GPA : %f\n", student_a.gpa );
}
o/p will be

First Name: Deo


Last Name: Dum
SSN : 2333234
GPA : 2009.20

Like other primitive data types, we can create an array of structures.

#include<stdio.h>

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

struct Point
{
int x, y;
};

int main()
{
// Create an array of structures
struct Point arr[10];

// Access array members


arr[0].x = 10;
arr[0].y = 20;
printf("%d %d", arr[0].x, arr[0].y);
return 0;
}
Output:
10 20

Like primitive types, we can have pointer to a structure. If we have a pointer to


structure, members are accessed using arrow ( -> ) operator.

#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {1, 2};

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

// p2 is a pointer to structure p1
struct Point *p2 = &p1;

// Accessing structure members using structure pointer


printf("%d %d", p2->x, p2->y);
return 0;
}
Output:
12
FEATURES IN STRUCTURE
 No Data Hiding: 
o C Structures do not permit data hiding. Structure members can be accessed by
any function, anywhere in the scope of the Structure.
 Functions inside Structure: 
o C structures do not permit functions inside Structure
 Static Members: 
o C Structures cannot have static members inside their body
 Access Modifiers: 
o C Programming language do not support access modifiers. So they cannot be
used in C Structures.

ADVANTAGES OF STRUCTURE:
A functional structure provides stability and efficiency, especially in large and
complex organizations, because everyone uses similar processes. This also allows
large businesses to take advantage of economies of scale.

DISADVANTAGE OF STRUCTURE:
o Since Goto statement is not used, the structure of the program needs to be
planned meticulously.
o Lack of Encapsulation.
o Same code repetition.
o Lack of information hiding.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

5.3 STRUCTURE WITHIN A STRUCTURE


Programming language has its own way of defining and describing structures. So
Nested structures as its name suggest in C is kind of defining one structure inside another
structure. Any member variables can be defined inside a structure and in turn, that structure
can further be moved into another structure. The variables inside a structure can be anything
like normal or pointer or anything and can be placed anywhere within the structure.

Nested Structure can be accessed in two ways:

1. Structure inside a structure in C using the pointer variable.


2. Structure inside a structure in C using a normal variable.

The syntax for creating a nested structure:


structure tagname_1
{
var_1;
var_2;
var_3;
.
.

var n;
structure tagname_2
{
var_1;
var_2;
var_3;
.
.
.

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

var_n;
}, mem1
} mem2;

Working of Nested Structure in C


From the above syntax, we can infer the fact that mem1 structure nested inside
member1 structure will contain the member or the variable to be accessed and everyone can
be accessed in a nested manner by using. (dot) operator.

mem2.mem1.var_1: This refers to the first member of the variable of the structure
tagname_1.
mem2.mem1.var_2: This refers to the second member of the variable of the structure
tagname_2.
We will take more examples to get clarity on how the syntax satisfies the working of the
nested structure.

Examples #1
struct employee
{
struct man
{
char name [20];
int age;
char dob[10];
} d;
int empid;
char desg[10];
} emp;

5.4 UNION:

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

 A union is a special data type available in C that allows to store different data
types in the same memory location.
 It can define a union with many members, but only one member can contain a
value at any given time. 
 Unions provide an efficient way of using the same memory location for
multiple-purpose.
DEFINING A UNION
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one member
for your program. The format of the union statement is as follows –

union [union tag] {


member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the union's
definition, before the final semicolon, you can specify one or more union variables but it is
optional. Here is the way you would define a union type named Data having three members i,
f, and str
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string
of characters. It means a single variable, i.e., same memory location, can be used to store
multiple types of data. You can use any built-in or user defined data types inside a union
based on your requirement.

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

The memory occupied by a union will be large enough to hold the largest member of
the union. For example, in the above example, Data type will occupy 20 bytes of memory
space because this is the maximum space which can be occupied by a character string. The
following example displays the total memory size occupied by the above union −

Sample Program
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result −

Memory size occupied by data : 20

ACCESSING UNION MEMBERS


To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the union
member that we wish to access. You would use the keyword union to define variables of
union type. The following example shows how to use unions in a program −

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

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

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


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

return 0;
}
When the above code is compiled and executed, it produces the following result −

data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

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

union Data {
int i;
float f;
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

char str[20];
};

int main( ) {

union Data data;

data.i = 10;
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;
}
When the above code is compiled and executed, it produces the following result −

data.i : 10
data.f : 220.500000
data.str : C Programming

DIFFERENCE BETWEEN STRUCTURE AND UNION

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

Structures, Unions, and Enumerated Types Structures


 An array is a collection of data items, all having the same data type and
accessed using a common name and an integer index into the collection.
 A struct is also a collection of data items, except with a struct the data items
can have different data types, and the individual fields within the struct are
accessed by name instead of an integer index.
 Structs are very powerful for bundling together data items that collectively
describe a thing, or are in some other way related to each other.
 Declaring New Structure Types and struct variables
 In order to use variables of type struct, it is first necessary to define the
particular type of struct to be used.

Tagged ( Named ) Structs


The most common and perhaps best way to define a new structure type involves
naming it, with a tag, as shown in the following example:
struct Part {
int number, on_hand;
char name [ NAME_LEN + 1 ];
double price;
};
In the example above, the tag for the newly defined struct is "Part", and the names of
the fields within the struct are number, on_hand, name, and price. Note that the fields can
have different types, although that is not necessary.
At this point "struct Part" is a valid data type, and so variables can be declared of this type:
struct Part p1, p2;
It is also possible to create a struct type and declare variables of the type at the same time:
struct Student {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} joe, sue, mary;

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

Now that struct Student is a declared type, additional variables of the same type can also be
created:
struct Student mike, carla;
It is also possible to create struct variables without creating a named struct type in the
process, however in this case it is not possible to create additional variables of the same type,
nor can they be passed to functions, etc. Even if other struct variables are created with the
same data types and field names in the same order, they are not considered the same type:
struct {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} alice, bill; // alice and bill are of the same type, but not the same as struct Student
struct {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} charlie, daniel; // charlie and daniel are the same type as each other, but not
anyone else.
Use of typedef with structs
 typedef is a powerful tool that allows programmers to define and then use their own
data types. For example:
 typedef int Integer;
 Integer nStudents, nCourses, studentID;
 Note that in the typedef statement, the newly defined type name goes in the place
where a variable name would normally go.
 There are a few benefits of using typedef with simple types such as the example
above:
 For readability, "Integer" may be easier to understand than "int".
 The typedef can be easily changed later, ( say to "typedef long int Integer;" ), which
would then affect all variables of the defined type.

Scope of struct type definitions

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

 The scope of struct type definitions ( with or without the use of typedef ) follows the
same rules as variable declarations.
 Obviously this means that the struct definition must be within scope before variables
of that type can be declared.
 If only one function needs to know about a particular struct definition, then it should
be defined inside that function, but if more than one function needs to know the
definition, then it should be defined globally. ( Even though the variables should still
normally be declared locally. )

typedef struct Student {


int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} Student;

Now that struct Student has been typedefed to the name "Student", additional
variables of the same type can also be created:
Student phil, georgina;
In this particular example the tag name and the newly defined type name are the same. This is
allowed, but not required. In fact it is not even necessary to have the tag name, so the
following would do the same thing:
typedef struct {
int nClasses;
char name [ NAME_LEN + 1 ];
double gpa;
} Student;
Initializing variables of type struct

NESTED STRUCTS
Structs can be nested, either with previously defined structs or with new internally
defined structs. In the latter case the struct names may not be necessary, but scoping rules still
apply. ( I.e. if a new struct type is created inside another struct, then the definition is only
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

known within that struct. ) For example, in the following code the Date struct is defined
independently to the Exam struct, but the score and time structs are defined internally to the
Exam struct::
struct Date {
int day, month, year; };

struct Exam {
int room, nStudents;

struct Date date;

struct {
int hour, minute;
bool AM;
} time;

typedef struct Score{


int part1, part2, total; } Score;

Score scores[ 100 ];


};
Many powerful and complicated data structures can be realized using pointers to
structs containing pointers. These will be covered in a later section of these notes.
Struct bit fields. On occasion it is desired to hold a number of small integer items in a
structure. To save space, the fields within a structure are not required to occupy a full word.
Instead, they can occupy a specified number of bits.
Multiple consecutive bit fields in a structure will share a single word of memory, insofar as
each field fits completely. This reduces storage requirements, at the expense of slower
execution.
If the next bit field does not fit in the currently unallocated portion of the current
word, then it will be put entirely into the next word. The remainder of the current word will
be wasted. The size of a bit field is indicated by appending a colon and the number of desired
bits after the field name. If a bit field size is specified as zero, it forces the next bit field to be
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

placed on a word boundary. These variables are more quickly accessed. The field name is
not required for zero length bit fields. Structure bit fields must be of an integral type. Most
implementations treat them as unsigned.
Example:
struct Packed_data {
unsigned int is_element:1; /* = 1 if element *
unsigned int atomic_number:8; /* Maximum 128 */
unsigned int is_reactant:1;
unsigned int is_product:1;
unsigned int is_catalyst:1;
unsigned int Stock_Index:16; /* Maximum 65,535 */
} chemical_inventory[ 10000 ];
Each data item in the above array takes up one 32-bit word ( with four bits wasted ),
for a total of 10,000 words of storage for the entire array, as opposed to 60,000 words of
storage if bitfields were not used.

ENUMERATED DATA TYPES


Enumerated data types are a special form of integers, with the following constraints:
Only certain pre-determined values are allowed.
Each valid value is assigned a name, which is then normally used instead of integer values
when working with this data type.
Enumerated types, variables, and typedefs, operate similarly to structs:
enum suits { CLUBS, HEARTS, SPADES, DIAMONDS, NOTRUMP } trump;
enum suits ew_bid, ns_bid;

typedef enum Direction{ NORTH, SOUTH, EAST, WEST } Direction;


Direction nextMove = NORTH;
Values may be assigned to specific enum value names.
Any names without assigned values will get one higher than the previous entry.
If the first name does not have an assigned value, it gets the value of zero.
It is even legal to assign the same value to more than one name.
Example:
enum Errors{ NONE=0, // Redundant. The first one would be zero anyway
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

MINOR1=100, MINOR2, MINOR3, // 100, 101, and 102


MAJOR1=1000, MAJOR2, DIVIDE_BY_ZERO=1000 }; // 1000, 1001, and
1000 again.
Because enumerated data types are integers, they can be used anywhere integers are allowed.
One of the best places in in switch statements:
switch( nextMove ) {
case NORTH:
y++;
break;
// etc.
The compiler will allow the use of ordinary integers with enumerated variables, e.g. trump =
2; , but it is bad practice.

UNIONS
Unions are declared, created, and used exactly the same as struts, EXCEPT for one key
difference:
Structs allocate enough space to store all of the fields in the struct. The first one is stored at
the beginning of the struct, the second is stored after that, and so on.
Unions only allocate enough space to store the largest field listed, and all fields are stored at
the same space - The beginning of the union.
This means that all fields in a union share the same space, which can be used for any listed
field but not more than one of them.
In order to know which union field is actually stored, unions are often nested inside of structs,
with an enumerated type indicating what is actually stored there. For example:
typedef struct Flight {
enum { PASSENGER, CARGO } type;
union {
int npassengers;
double tonnages; // Units are not necessarily tons.
} cargo;
} Flight;

Flight flights[ 1000 ];


Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

flights[ 42 ].type = PASSENGER;


flights[ 42 ].cargo.npassengers = 150;

flights[ 20 ].type = CARGO;


flights[ 20 ].cargo.tonnages = 356.78;
The example above does not actually save any space, because the 4 bytes saved by
using a union instead of a struct for the cargo is lost by the int needed for the enumerated
type. However a lot of space could potentially be saved if the items in the union were larger,
such as nested structs or large arrays.
Unions are sometimes also used to break up larger data items into smaller pieces, such
as this code to extract four 8-bit bytes from a 32-bit int:
int nRead;

union {
unsigned int n;
unsigned char c[ 4 ];
} data;

// ( Code to read in nRead, from the user or a file, has been omitted in this
example )

data.n = nRead;
for( int i = 0; i < 4; i++ )
printf( "Byte number %d of %ud is %ud\n", i, nRead, data.c[ i ] );

5.6 STORAGE CLASSES


A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have four
different storage classes in a C program

 auto
 register
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

 static
 extern

The auto Storage Class


The auto storage class is the default storage class for all local variables.

{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be
used within functions, i.e., local variables.

THE REGISTER STORAGE CLASS


The register storage class 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;
}
The register should only be used for variables that require quick access such as counters. It
should also be noted that defining 'register' does not mean that the variable will be stored in a
register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.

THE STATIC STORAGE CLASS


The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.

In C programming, when static is used on a global variable, it causes only one copy of that
member to be shared by all the objects of its class.
#include <stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */

main() {

while(count--) {
func();
}

return 0;
}

/* function definition */
void func( void ) {

static int i = 5; /* local static variable */


i++;

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


}
When the above code is compiled and executed, it produces the following result

i is 6 and count is 4
i is 7 and count is 3
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

THE EXTERN STORAGE CLASS


The extern storage class 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 however, it points
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 also be
used in other files, then extern will be used in another file to provide the reference of defined
variable or function. Just for understanding, extern is used to declare a global variable or
function in another file.

The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions as explained below.

First File: main.c

#include <stdio.h>
int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}

Second File: support.c

#include <stdio.h>
extern int count;

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in
the first file, main.c. Now, compile these two files as follows

$gcc main.c support.c


It will produce the executable program a.out. When this program is executed, it produces the
following result
count is 5

Storage classes in C
Storage Storage Initial Value Scope Life
Specifier
Auto Stack Garbage Within block End of block
Extern Data segment Zero Global multiple Till end of
files program
Static Data segment Zero Within block Till end of the
program
Register CPU register Garbage Within block End of block

5.6 PRE-PROCESSOR DIRECTIVES

The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it
instructs the compiler to do required pre-processing before the actual compilation. We'll
refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in the first
column. The following section lists down all the important preprocessor directives −

Sr.No. Directive & Description

1 #define
Substitutes a preprocessor macro.
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.

9 #endif
Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11
#pragma
Issues special commands to the compiler, using a standardized method.

PREPROCESSORS EXAMPLES

Analyze the following examples to understand various directives.

#define MAX_ARRAY_LENGTH 20

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.

#include <stdio.h>

#include "myheader.h"

These directives tell the CPP to get stdio.h from System Libraries and add the text to the
current source file. The next line tells CPP to get myheader.h from the local directory and
add the content to the current source file.

#undef FILE_SIZE

#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE

#define MESSAGE "You wish!"

#endif

It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

#ifdef DEBUG
/* Your debugging statements here */
#endif

It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if
you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define
DEBUG, so you can turn debugging on and off on the fly during compilation.

PREDEFINED MACROS

ANSI C defines a number of macros. Although each one is available for use in
programming, the predefined macros should not be directly modified.

Sr.No. Macro & Description

1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

2 __TIME__
The current time as a character literal in "HH:MM:SS" format.

3 __FILE__
This contains the current filename as a string literal.

4 __LINE__
This contains the current line number as a decimal constant.

5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.

Let's try the following example

#include <stdio.h>

int main() {

printf("File :%s\n", __FILE__ );

printf("Date :%s\n", __DATE__ );

printf("Time :%s\n", __TIME__ );

printf("Line :%d\n", __LINE__ );

printf("ANSI :%d\n", __STDC__ );

When the above code in a file test.c is compiled and executed, it produces the following
result

File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

ANSI :1

PREPROCESSOR OPERATORS

The C preprocessor offers the following operators to help create macros −

The Macro Continuation (\) Operator

A macro is normally confined to a single line. The macro continuation operator (\) is
used to continue a macro that is too long for a single line. For example

#define message_for(a, b) \

printf(#a " and " #b ": We love you!\n")

The Stringize (#) Operator

The stringize or number-sign operator ( '#' ), when used within a macro definition,
converts a macro parameter into a string constant. This operator may be used only in a
macro having a specified argument or parameter list. For example −

#include <stdio.h>

#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")

int main(void) {
message_for(Carole, Debra);
return 0;
}

When the above code is compiled and executed, it produces the following result

Carole and Debra: We love you!

The Token Pasting (##) Operator

The token-pasting operator (##) within a macro definition combines two arguments. It
permits two separate tokens in the macro definition to be joined into a single token. For
example

#include <stdio.h>
Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

#define tokenpaster(n) printf ("token" #n " = %d", token##n)


int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}

When the above code is compiled and executed, it produces the following result −

token34 = 40

It happened so because this example results in the following actual output from the
preprocessor

printf ("token34 = %d", token34);

This example shows the concatenation of token##n into token34 and here we have used
both stringize and token-pasting.

The Defined() Operator

The preprocessor defined operator is used in constant expressions to determine if an


identifier is defined using #define. If the specified identifier is defined, the value is true
(non-zero). If the symbol is not defined, the value is false (zero). The defined operator is
specified as follows

#include <stdio.h>

#if !defined (MESSAGE)


#define MESSAGE "You wish!"
#endif

int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}

When the above code is compiled and executed, it produces the following result −

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.
Programming in C-Structures and Unions

Here is the message: You wish!

PARAMETERIZED MACROS

One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a number as
follows

int square(int x) {

return x * x;

We can rewrite above the code using a macro as follows

#define square(x) ((x) * (x))

Macros with arguments must be defined using the #define directive before they can be used.
The argument list is enclosed in parentheses and must immediately follow the macro name.
Spaces are not allowed between the macro name and open parenthesis. For example

#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}

When the above code is compiled and executed, it produces the following result

Max between 20 and 10 is 20

REFERENCE BOOK
1. E. Balaguruswamy Programming in ANSI C 6th Edition. P.191-198
2. Ashok N. Kamthane Programming in C.P. P.436-13
3. C Tutorial Points Link : https://www.tutorialspoint.com/cprogramming/c_structures.htm
4. C Geeks of Geeks Link : https://www.geeksforgeeks.org/structures-c/

Notes Prepared by
A.Bathsheba Parimala
Assistant Professor Dept. Of BCA
St. Johns College, Palayamkottai.

You might also like