0% found this document useful (0 votes)
21 views

UNIT 4C Programming

UNIT 4 C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

UNIT 4C Programming

UNIT 4 C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1

UNIT-IV
STRUCTURES AND UNIONS

Structures and Unions Structure - Nested structures – Pointer to Structures – Array of


structures – Self-referential structures – Dynamic memory allocation – Typedef-Unions – Union
of Structures

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:

DECLARING STRUCTURE VARIABLE


We can declare variable for the structure, so that we can access the member of structure easily.
There are two ways to declare structure variable:
2

1. By struct keyword within main() function


2. By declaring variable at the time of defining structure.
1st way:
Let's see the example to declare structure variable by struct keyword.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
2nd way:
Let's see another way to declare variable at the time of defining structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Which approach is good:
 But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare
the structure variable many times.
 If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in
main() function.

ACCESSING MEMBERS OF STRUCTURE


There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)

#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;

/* print Book1 info */


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

/* print Book2 info */


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

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;

Accessing Nested Structure


We can access the member of nested structure by Outer_Structure.Nested_Structure.member as
given below:
1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
C Nested Structure example
Let's see a simple example of nested structure in C language.
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
void main( )
{
5

//storing employee information


e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;

//printing first employee information


printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
}

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;
};

Let's see the example to define union for employee in c.


union employee
{ int id;
char name[50];
float salary;
};
6

Advantage of union over structure


 It occupies less memory because it occupies the memory of largest member only.
Disadvantage of union over structure
 It can store data in one member only.

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.

C – STORAGE CLASS SPECIFIERS


Storage class specifiers in C language tells the compiler where to store a variable, how to store
the variable, what is the initial value of the variable and life time of the variable.
Syntax:
storage_specifier data_type variable _name;
7

Types of Storage Class Specifiers in C:


There are 4 storage class specifiers available in C language. They are,
1. auto
2. extern
3. static
4. register
Storage Specifier Description
Storage place: CPU Memory
Initial/default value: Garbage value
auto
Scope: local
Life: Within the function only.
Storage place: CPU memory
Initial/default value: Zero
extern Scope: Global
Life: Till the end of the main program. Variable definition might
be anywhere in the C program.
Storage place: CPU memory
Initial/default value: Zero
static Scope: local
Life: Retains the value of the variable between different function
calls.
Storage place: Register memory
Initial/default value: Garbage value
register
Scope: local
Life: Within the function only.
1. auto variable in C:
The scope of this auto variable is within the function only. It is equivalent to local variable. All
local variables are auto variables by default.
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}

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.

First File: main.c


#include <stdio.h>
int count ;
extern void write_extern();
void main() {
count = 5;
write_extern();
}

Second File: support.c


#include <stdio.h>
9

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. It will produce the executable program a.out. When this program is executed, it
produces the following result −
count is 5

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
(#)

Note: Proprocessor direcives are executed before compilation.

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( );

#pragma startup function1


#pragma exit 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

You might also like