SlideShare a Scribd company logo
1 of 32
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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 : %sn", Book1.title);
printf( "Book 1 author : %sn", Book1.author);
printf( "Book 1 subject : %sn", Book1.subject);
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
printf( "Book 1 book_id : %dn", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %sn", Book2.title);
printf( "Book 2 author : %sn", Book2.author);
printf( "Book 2 subject : %sn", Book2.subject);
printf( "Book 2 book_id : %dn", 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:
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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];
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
#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: %sn", student_a.firstName );
printf( "Last Name: %sn", student_a.lastName );
printf( "SNN : %sn", student_a.SSN );
printf( "GPA : %fn", 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>
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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};
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
// 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:
1 2
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.
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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;
.
.
.
var_n;
}, mem1
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
} 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:
 A union is a special data type available in C that allows to store different data
types in the same memory location.
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
 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.
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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 : %dn", 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>
union Data {
int i;
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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 : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", 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;
char str[20];
};
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", 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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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;
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
 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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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 ];
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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 %udn", 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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
 register
 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.
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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 %dn", i, count);
}
When the above code is compiled and executed, it produces the following result
i is 6 and count is 4
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
i is 7 and count is 3
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;
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
void write_extern(void) {
printf("count is %dn", 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
Specifier
Storage Initial Value Scope Life
Auto Stack Garbage Within block End of block
Extern Data segment Zero Global multiple
files
Till end of
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 −
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
Sr.No. Directive & Description
1
#define
Substitutes a preprocessor macro.
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
1
__DATE__
The current date as a character literal in "MMM DD YYYY" format.
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 :%sn", __FILE__ );
printf("Date :%sn", __DATE__ );
printf("Time :%sn", __TIME__ );
printf("Line :%dn", __LINE__ );
printf("ANSI :%dn", __STDC__ );
}
When the above code in a file test.c is compiled and executed, it produces the following
result
File :test.c
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
Date :Jun 2 2012
Time :03:36:24
Line :8
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!
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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>
#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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
int main(void) {
printf("Here is the message: %sn", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
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 %dn", 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
Programming in C-Structures and Unions
NotesPreparedby
A.BathshebaParimala
AssistantProfessorDept.Of BCA
St. JohnsCollege,Palayamkottai.
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/

More Related Content

What's hot

Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and StructuresGem WeBlog
 
Relational Database Design
Relational Database DesignRelational Database Design
Relational Database DesignPrabu U
 
Structure in c language
Structure in c languageStructure in c language
Structure in c languagesangrampatil81
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9patcha535
 
Genetic Programming with Polymorphic Types and Higher-Order Functions
Genetic Programming with Polymorphic Types and Higher-Order FunctionsGenetic Programming with Polymorphic Types and Higher-Order Functions
Genetic Programming with Polymorphic Types and Higher-Order Functionsfbinard
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationGem WeBlog
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionJI Ruan
 
Object oriented programming interview questions
Object oriented programming interview questionsObject oriented programming interview questions
Object oriented programming interview questionsKeet Sugathadasa
 
CSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: AbstractionCSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: AbstractionJI Ruan
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++Davinder Kaur
 
Tcs Technical Question
Tcs Technical QuestionTcs Technical Question
Tcs Technical QuestionVinay Kumar
 
Function pointer
Function pointerFunction pointer
Function pointerGem WeBlog
 

What's hot (20)

Unit 3
Unit 3Unit 3
Unit 3
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
Array Cont
Array ContArray Cont
Array Cont
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Relational Database Design
Relational Database DesignRelational Database Design
Relational Database Design
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 
p138-jiang
p138-jiangp138-jiang
p138-jiang
 
Genetic Programming with Polymorphic Types and Higher-Order Functions
Genetic Programming with Polymorphic Types and Higher-Order FunctionsGenetic Programming with Polymorphic Types and Higher-Order Functions
Genetic Programming with Polymorphic Types and Higher-Order Functions
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: Abstraction
 
Pl sql chapter 3 part_1
Pl sql chapter 3 part_1Pl sql chapter 3 part_1
Pl sql chapter 3 part_1
 
Object oriented programming interview questions
Object oriented programming interview questionsObject oriented programming interview questions
Object oriented programming interview questions
 
CSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: AbstractionCSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: Abstraction
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Tcs Technical Question
Tcs Technical QuestionTcs Technical Question
Tcs Technical Question
 
Function pointer
Function pointerFunction pointer
Function pointer
 
SEMINAR
SEMINARSEMINAR
SEMINAR
 

Similar to C Structures & Unions Guide

Similar to C Structures & Unions Guide (20)

Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
Structures
StructuresStructures
Structures
 
Structure In C
Structure In CStructure In C
Structure In C
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
Ocs752 unit 5
Ocs752   unit 5Ocs752   unit 5
Ocs752 unit 5
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
Structures
StructuresStructures
Structures
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 

More from Bathshebaparimala (20)

An enhanced liver stages classification in 3 d ct and 3d-us images using glrl...
An enhanced liver stages classification in 3 d ct and 3d-us images using glrl...An enhanced liver stages classification in 3 d ct and 3d-us images using glrl...
An enhanced liver stages classification in 3 d ct and 3d-us images using glrl...
 
Assessment
AssessmentAssessment
Assessment
 
Normalization
NormalizationNormalization
Normalization
 
Protocols and its standards
Protocols and its standardsProtocols and its standards
Protocols and its standards
 
Unit v
Unit vUnit v
Unit v
 
Hint for transmission media
Hint for transmission mediaHint for transmission media
Hint for transmission media
 
Osi model detail description
Osi model  detail descriptionOsi model  detail description
Osi model detail description
 
Creating a rainbow using graphics programming in c
Creating a rainbow using graphics programming in cCreating a rainbow using graphics programming in c
Creating a rainbow using graphics programming in c
 
Network layer
Network layerNetwork layer
Network layer
 
Microprocessor
MicroprocessorMicroprocessor
Microprocessor
 
Assembly language
Assembly languageAssembly language
Assembly language
 
Routing
RoutingRouting
Routing
 
Transport layer
Transport layerTransport layer
Transport layer
 
Generation of Computer Network
Generation of Computer NetworkGeneration of Computer Network
Generation of Computer Network
 
Network -Lecture Notes
Network -Lecture NotesNetwork -Lecture Notes
Network -Lecture Notes
 
Segmentation of Machine learning Algorithm
Segmentation of Machine learning AlgorithmSegmentation of Machine learning Algorithm
Segmentation of Machine learning Algorithm
 
Osireferencemodel
OsireferencemodelOsireferencemodel
Osireferencemodel
 
Transmission media
Transmission mediaTransmission media
Transmission media
 
Osi model
Osi modelOsi model
Osi model
 
Relational dbms
Relational dbmsRelational dbms
Relational dbms
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 

C Structures & Unions Guide

  • 1. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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
  • 2. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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 : %sn", Book1.title); printf( "Book 1 author : %sn", Book1.author); printf( "Book 1 subject : %sn", Book1.subject);
  • 3. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. printf( "Book 1 book_id : %dn", Book1.book_id); /* print Book2 info */ printf( "Book 2 title : %sn", Book2.title); printf( "Book 2 author : %sn", Book2.author); printf( "Book 2 subject : %sn", Book2.subject); printf( "Book 2 book_id : %dn", 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:
  • 4. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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];
  • 5. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. #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: %sn", student_a.firstName ); printf( "Last Name: %sn", student_a.lastName ); printf( "SNN : %sn", student_a.SSN ); printf( "GPA : %fn", 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>
  • 6. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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};
  • 7. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. // 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: 1 2 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.
  • 8. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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; . . . var_n; }, mem1
  • 9. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. } 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:  A union is a special data type available in C that allows to store different data types in the same memory location.
  • 10. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai.  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. 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
  • 11. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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 : %dn", 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> union Data { int i;
  • 12. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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 : %dn", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", 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; char str[20]; };
  • 13. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", 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
  • 14. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai.
  • 15. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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;
  • 16. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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
  • 17. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai.  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
  • 18. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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
  • 19. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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
  • 20. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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 ];
  • 21. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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 %udn", 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
  • 22. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai.  register  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.
  • 23. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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 %dn", i, count); } When the above code is compiled and executed, it produces the following result i is 6 and count is 4
  • 24. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. i is 7 and count is 3 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;
  • 25. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. void write_extern(void) { printf("count is %dn", 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 Specifier Storage Initial Value Scope Life Auto Stack Garbage Within block End of block Extern Data segment Zero Global multiple files Till end of 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 −
  • 26. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. Sr.No. Directive & Description 1 #define Substitutes a preprocessor macro. 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
  • 27. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. Analyze the following examples to understand various directives. #define MAX_ARRAY_LENGTH 20 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
  • 28. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 1 __DATE__ The current date as a character literal in "MMM DD YYYY" format. 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 :%sn", __FILE__ ); printf("Date :%sn", __DATE__ ); printf("Time :%sn", __TIME__ ); printf("Line :%dn", __LINE__ ); printf("ANSI :%dn", __STDC__ ); } When the above code in a file test.c is compiled and executed, it produces the following result File :test.c
  • 29. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. Date :Jun 2 2012 Time :03:36:24 Line :8 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!
  • 30. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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> #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
  • 31. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. int main(void) { printf("Here is the message: %sn", MESSAGE); return 0; } When the above code is compiled and executed, it produces the following result − 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 %dn", 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
  • 32. Programming in C-Structures and Unions NotesPreparedby A.BathshebaParimala AssistantProfessorDept.Of BCA St. JohnsCollege,Palayamkottai. 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/