UNIT 4C Programming
UNIT 4C Programming
UNIT-IV
STRUCTURES AND UNIONS
STRUCTURE:
Structure is a collection of variables of different types under a single name. Structures are
used to represent a record. Suppose you want to keep track of your books in a library. We might
want to track the following attributes about each book −
Title
Author
Subject
Book ID
DEFINING STRUCTURE
The struct keyword is used to define structure. Let's see the syntax to define structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define structure for employee in c.
struct employee
{ int id;
char name[50];
float salary;
};
Here, struct is the keyword, employee is the tag name of structure; id, name and salary are the
members or fields of the structure. Let's understand it by the diagram given below:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
void 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");
3
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;
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
NESTED STRUCTURE IN C
Nested structure in c language can have another structure as a member. There are two ways to
define nested structure in c language:
1. By separate structure
2. By Embedded structure
1) Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure
as a member. Let's see the code of nested structure.
struct Date
{
int dd;
int mm;
int yyyy;
};
4
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
As we can see, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
We can define structure within the structure also. It requires less code than previous way. But
it can't be used in many structures.
1. struct Employee
2. {
3. int id;
4. char name[20];
5. struct Date
6. {
7. int dd;
8. int mm;
9. int yyyy;
10. }doj;
11. }emp1;
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining : 10/11/2014
C UNION:
Like structure, Union in c language is a user defined datatype that is used to hold
different type of elements. It occupies the memory of largest member only. It shares memory of
largest member.
Defining union
The union keyword is used to define union. Let's see the syntax to define union in c.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
C Union example
Let's see a simple example of union in C language.
#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
void main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
}
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
As we can see, id gets garbage value because name has large memory size. So only name will
have actual value.
void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
i++;
8
}
Output:
0000
2. static variable in C:
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program. Therefore, making local variables static allows them to maintain their
values between function calls.
/C static example
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( "%d ", i ) ;
i++;
}
Output:
0123
3. extern variable in C:
The extern storage class is used to give a reference of a global variable that is visible to
ALL the program files. 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.
4. register variable in C:
Register variables are also local variables, but stored in register memory. Whereas, auto
variables are stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are
stored in register memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits,
32 bits or 64 bits)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Note:
For faster access of a variable, it is better to go for register specifiers rather than auto
specifiers.
Because, register variables are stored in register memory whereas auto variables are
stored in main CPU memory.
Only few variables can be stored in register memory. So, we can use variables as register
that are used very often in a C program.
10
C PREPROCESSOR DIRECTIVES
C Preprocessor is just a text substitution tool and it instructs the compiler to do require pre-
processing before the actual compilation. All preprocessor commands begin with a hash symbol
(#)
All preprocessor directives starts with hash # symbol. Let's see a list of preprocessor directives.
#include
#define
#undef
#ifdef
#ifndef
#if
#else
#elif
#endif
#error
#pragma
1. C Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
11
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14. The function-like macro
looks like function call. For example:
#define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name.
#include <stdio.h>
#define PI 3.14
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("%f",PI
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
2. C #include
The #include preprocessor directive is used to paste code of given file into current file. It is
used include system-defined and user-defined header files. By the use of #include directive, we
provide information to the preprocessor where to look for the header files. There are two variants
to use #include directive.
1. #include <filename>
2. #include "filename"
The #include <filename> tells the compiler to look for the directory where system header files
are held. In UNIX, it is \usr\include directory.
The #include "filename" tells the compiler to look in the current directory from where program
is running.
3. C #undef
The #undef preprocessor directive is used to undefine the constant or macro defined by #define.
Syntax:
1. #undef token
Let's see a simple example to define and undefine a constant.
1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }
Output:
Compile Time Error: 'PI' undeclared
4. C #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code otherwise #else code is executed, if present.
Syntax:
#ifdef MACRO
//successful code
#else
12
//else code
#endif
Let's see a simple example to use #ifdef preprocessor directive.
#include <stdio.h>
#include <conio.h>
#define NOINPUT
void main() {
int a=0;
#ifdef NOINPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Value of a: 2
5. C #ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes
the code otherwise #else code is executed, if present.
Syntax:
#ifndef MACRO
//successful code
#else
//else code
#endif
Let's see a simple example to use #ifndef preprocessor directive.
#include <stdio.h>
#include <conio.h>
#define INPUT
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Enter a:5
13
Value of a: 5
6. C #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.
Syntax with #elif and #else:
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
7. C #else
The #else preprocessor directive evaluates the expression or condition if condition of #if is
false. It can be used with #if, #elif, #ifdef and #ifndef directives. Let's see a simple example to
use #else preprocessor directive.
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}
Output:
Value of Number is non-zero
8.C #error
The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process. Let's see a simple example to use #error
preprocessor directive.
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
14
Output:
Compile Time Error: First include then compile
9. C #pragma
Pragma is used to call a function before and after main function in a C program.
#include <stdio.h>
void function1( );
void function2( );
void main( )
{
printf ( "\n Now we are in main function" ) ;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}
Output:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main function