C Programming Structures Union
C Programming Structures Union
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.
1.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
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;
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 structure member that we wish
Page | 1
Programmi in C-Structures and Unions
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;
Page | 2
Programmi in C-Structures and Unions
return 0;
}
When the above code is compiled and executed, it produces the following result.
Declaration of a Structure:
Page | 3
Programmi 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.
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.
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];
#include <stdio.h>
struct student {
char firstName[20];
Page | 4
Programmi in C-Structures and Unions
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;
#include<stdio.h>
struct Point
{
int x, y;
Page | 5
Programmi in C-Structures and Unions
};
int main()
{
// Create an array of structures
struct Point arr[10];
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};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
Page | 6
Programmi in C-Structures and Unions
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 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.
var n;
structure tagname_2
{
var_1;
var_2;
var_3;
.
.
.
var_n;
}, mem1
} mem2;
Page | 8
Programmi in C-Structures and Unions
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;
1.4 UNION:
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
Page | 9
Programmi in C-Structures and Unions
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 –
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 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;
Page | 10
Programmi in C-Structures and Unions
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 −
Sample Program
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
Page | 11
Programmi in C-Structures and Unions
data.f = 220.5;
strcpy( data.str, "C Programming");
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];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
Page | 12
Programmi in C-Structures and Unions
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
Page | 13
Programmi in C-Structures and Unions
Page | 14
Programmi in C-Structures and Unions
Page | 15
Programmi 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. )
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:
Page | 16
Programmi in C-Structures and Unions
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 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 {
int hour, minute;
bool AM;
} time;
Page | 17
Programmi in C-Structures and Unions
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 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.
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;
Page | 19
Programmi in C-Structures and Unions
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 ] );
Page | 20
Programmi in C-Structures and Unions
auto
register
static
extern
{
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.
{
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.
Page | 21
Programmi in C-Structures and Unions
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.
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);
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
Page | 22
Programmi in C-Structures and Unions
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
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
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.
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Page | 23
Programmi in C-Structures and Unions
#include <stdio.h>
extern int count;
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
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
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 −
Page | 24
Programmi in C-Structures and Unions
Page | 25
Programmi in C-Structures and Unions
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.
Page | 26
Programmi in C-Structures and Unions
PREPROCESSORS EXAMPLES
#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
#ifndef MESSAGE
#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.
Page | 27
Programmi in C-Structures and Unions
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.
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.
#include <stdio.h>
int main() {
}
Page | 28
Programmi in C-Structures and Unions
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
ANSI :1
PREPROCESSOR OPERATORS:
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) \
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.
Page | 29
Programmi in C-Structures and Unions
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
This example shows the concatenation of token##n into token34 and here we have used
both stringize and token-pasting.
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>
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
Page | 30
Programmi in C-Structures and Unions
When the above code is compiled and executed, it produces the following result −
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;
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
REFERENCE BOOK
1. Youtude.
2. Google Bard (A.I)
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/
Page | 31