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

Lesson12-Structures, Unions, Enums and Bitfields

Uploaded by

manasabezawada04
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lesson12-Structures, Unions, Enums and Bitfields

Uploaded by

manasabezawada04
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 32

Structures, Unions,

enumerations and 12
bitfields
0

Chapter Outline
Chapter Outline
“United we stand, divided we fall."
-- Aesop (620 -560 B.C.) Structures.
Structures.
Introduction.
Introduction.
Working with structures.
Working with structures.
Nested structures.
Nested structures.
Structures and arrays.
Structures and arrays.
Structures and pointers.
Structures and pointers.
Structures and functions.
Structures and functions.
We cannot afford to be separate. . . . We have
Unions.
to see that all of us are in the same boat. Unions.
-- Dorothy Height Enumerated data type.
Enumerated data type.
Bitfields.
Bitfields.

"The minute we become an integrated whole, we


look through the same eyes and we see a whole
different world together."
-- Azizah Al-Hibri
12.1.1. Introduction to structures
Suppose we want to represent a record in a file. A record is a collection of data items, each of different
data type. Then we require a different data type that can represent a record. That data type is called as a
structure.
Interview question #1
What is a structure?
Structure is heterogeneous collection of data items stored in contiguous memory
locations referred by same name
This definition has the following parts:
 Structure consists of heterogeneous data items. That is, all the data items (or members of
structure) stored in a structure are of different types.
 All members are stored in contiguous locations. That is, all members are stored one after other
in successive locations of memory (based on size of type of data items). Of course, fixed amount
of memory is allocated to a structure as a block of bytes.
 All data items referred by same name. That is, each data item can be identified with the same
name.

12.1.2. Working with structures


In order to work with a structure, one should do these things:
 Declare its prototype.
 Create variable(s) of that structure.
 Initialize and access the members of that structure.

12.1.2.1. Declaring a structure


A structure is a user-defined data type or an ADT. As a user-defined data type, the structure groups
different types of data items into a single entity. Each type of data item is also referred to as a member of
structure. A structure can be declared as follows:

struct <tag>
{
<data type1> <member(s)>;
<data type2> <member(s)>;
:
:
<data typeN> <member(s)>;
};
In this syntax,
 struct is the keyword. <tag>, an optional one, serves as a name for this structure. It is used to
declare variable of the same structure type. It should be a valid identifier. The first line of this
declaration is called as structure header.

http://pradeeppearlz.blogspot.com 2 User-Defined Data types


 All the members of the structure should be enclosed in curly braces. These members may be
variables, constants, arrays, pointers and even other structures too. If there are more members of
same type, those should be separated with commas. All the declarations in the curly braces
collectively referred to as structure body.
It is important to note that the structure declaration should be ended with a semi colon. The structure
name or members of structure may be omitted, but both, should not be omitted. The declaration of
structure describes prototype or blue print or template of a structure.
Point to ponder #1
Structure declaration never assures the allocation of memory for it; only creation of a variable of that
type of structure assures it.

Ex: struct student


{
int rno,age;
char name[15],sex;
float fees;
};

In this example, the structure student consists of the members: rno and age as integers, name and sex as
of char type and fees as of type float. However, the tag and names of members can be used as ordinary
variables with out any conflict in a program. Usually, this declaration can be placed at the top of source
code file, i.e., before the main().
Point to ponder #2
Declaration of structure outside of all functions never makes it global.

12.1.2.2. Creating a structure variable


After the declaration of structure, a variable of that type of structure should be created in order to access
the members of structure. The creation of variable takes the following form:

struct <tag> <var1,var2…varN>;

In this syntax,
struct is the keyword. <tag> is the name of the structure. <var1, var2 … varN> should be valid
identifiers.
Ex: struct student stud1,stud2;
The above statement declares two structure variables of type student: stud1, stud2. Usually, this
statement can be placed in body of main(). Once the variables are created, memory will be allocated for
them. The size of each variable is the sum of all the sizes of members of structure.

There are different ways to create variables:

http://pradeeppearlz.blogspot.com 3 User-Defined Data types


struct student struct student
{ 1 { 2
int rno,age; int rno,age;
char name[15],sex; char name[15],sex;
float fees; float fees;
}stud1,stud2; //creation of variables };
struct student stud1,stud2;
struct student typedef struct student
{ 3 { 4
int rno,age; int rno,age;
char name[15],sex; char name[15],sex;
float fees; float fees;
}; }STUDENTRECORD;
typedef struct student STUDENTRECORD; STUDENTRECORD stud1,stud2;
//renames the structure student //creation of variables
STUDENTRECORD stud1,stud2;
//creation of variables
typedef struct struct
{ { 6
5
int rno,age; int rno,age;
char name[15],sex; char name[15],sex;
float fees; float fees;
}STUDENTRECORD; }stud1,stud2;
STUDENTRECORD stud1,stud2; //creation of variables
//creation of variables
1) In method-1 and method-6, the structure variables are declared before the semicolon at the end of
structure declaration.
2) In method-3,method-4 and method-5, the structure variables are declared with the help of their
respective aliases (duplicate names).
3) The creation of structure variables in method-2 can be done outside of main() or within the main().
Interview question #2
Would the following declaration work?
What is the purpose of typedef?
typedef struct s
The typedef is the keyword that is used to define new data types that are equivalent to existing data
{
intOnce
types. a; a user-defined data type is declared, then new variables, arrays, structures and so on can
float b;
be declared in terms of these new data types.
}s;
Yes. We can declare a structure variable same as the name of structure.
typedef <data type> <new type>;

Point
Ex: to ponder
typedef#3unsigned long int ULONG;
This The size
typeofULONG
dataquestion
Interview
a structure variable is not always equal to sum of sizes of all members of structure.
#3 provides a short and meaningful way to call the data type: unsigned long int.
http://pradeeppearlz.blogspot.com 4 variables.
Now, the new data type ULONG can be used to declare User-Defined Data types
ULONG a,b,c; // variables are of type unsigned long int
Interview question #4
Why the ‘sizeof’ operator does sometimes results larger size than the calculated size for a
structure?
Padding (also called as buffering) is an important issue associated with structures. There may be some
alignment requirements enforced by the environment. E.g., ints may require to be aligned at even
numbered addresses and longs at address numbers divisible by 4. This is because, enforcing such
alignment boundaries help increase the access speed of the data stored in the memory and treat them
as a unit. E.g., in 8086 systems, a word size is 2 bytes. If a word is stored (i.e., aligned to start) in an
even address, the bytes can be read at a time. On the other hand, if it starts at an odd address, it is
accessed by two reads- obvious efficiency/time degradation. This leads to padding of bytes in the
structure. Due to this padding, the value returned by sizeof may not equal to sum of sizes of individual
structure members.

12.1.2.3. Initializing and accessing members of a structure


Membership operator (.): The members of a structure can be accessed with the help of membership
operator (.). The members of structure can be accessed with the help of membership operator or dot or
period as follows:
<structure_variable>.<member_name>

In this syntax,
<structure_variable> is the variable that is declared earlier.
<member_name> is the name of the member inside the body of structure.
Ex: The members of structure student are accessed with the help of structure variable stud1 and stud2 as
follows:
stud1.rno=26; stud2.rno=4;
stud1.age=18; stud2.age=18;
strcpy(stud1.name,”vamsee”); strcpy(stud2.name,”Sujitha”);
stud1.sex=’m’; stud2.sex=’f’;
stud1.fees=27500.00; stud2.fees=27500.00;

http://pradeeppearlz.blogspot.com 5 User-Defined Data types


Initializing members of structure:
Once structure is declared and a variable of that structure type is created, the members in that structure
can be initialized with the help of that structure variable. This can be done in two ways:
1. By using assignment operator.
2. By using scanf() statement
By using assignment operator
A structure can be initialized in its declaration itself with list of initializers enclosed within the curly braces.
Each initializer must be a constant and the order and type of each initializer must match with the order
and type of each member in declaration.
Ex: The above two structure variables stud1 and stud2 of structure type student can be intialized as
follows:
struct student stud1={13,18,”Balaji”,’m’,27500};
struct student stud2={5,18,”Sravani”,’f’,27500};
The above two variables can also be initialized as follows:
struct student
{
int rno,age;
char name[15],sex;
float fees;
}stud1={13,18,”Balaji”,’m’,27500},stud2={5,18,”Sravani”,’f’,27500};
The memory map for the structure variable stud1 is as follows:

stud1
sizeof(stud1)=2+2+15+1+4=24 bytes

rno (2bytes) age (2 bytes) name(15 bytes) sex (1 byte) fees(4 bytes)

13 18 Balaji m 27500.00

Note:
A structure variable may be initialzed by means of assigning another structure variable of similar type.
E.g.,
struct student stud3=stud2;
assigns the data of stud2 to stud3. But, the structure variable at the right side of the assignment
statement has to be declared and initialized before the assignment.
By using scanf() statement
The input statement scanf() can be used to initialize the members of structure variables. scanf() function
can take members as arguments. Each member can be preceded with dot operator that is preceded with
structure variable. While reading members from keyboard, there is no necessity of reading these in the
same order as they are in structure declaration.
Ex: The structure variable stud1 of structure type student can be used to read all the members of
structure as follows:
scanf(“%d%d%s\n%c%f”,&stud1.rno,&stud1.age,stud1.name,&stud1.sex,&stud1.fees);
http://pradeeppearlz.blogspot.com 6 User-Defined Data types
Program #1 Program #2
/* program to read 3 student details and /* program to read 2 Employee details and
print them*/ print them*/
#include<stdio.h> #include<stdio.h>
struct student main()
{ {
int rno,age; typedef struct employee
char name[15],sex; {
float fees; int empno,experience;
}; float salary;
main() char *ename,*designation;
{ }EMPRECORD;
struct student stud1,stud2;
struct student EMPRECORD e1,e2,e3;
stud3={3,18,”Sirisha”,’f’,27500.00};
printf(“\n enter first student rno , name , age , printf(“\n enter first employee number, name,
sex and fees”); designation, salary and work experience”);
scanf(“%d%s%d\n%c%f”,&stud1.rno, scanf(“%d%s%s%f%d”,&e1.empno,
stud1.name, &stud1.age, &stud1.sex, e1.ename, e1.designation, &e1.salary,
&stud1.fees); &e1.experience);

printf(“\n enter second student rno , name , age printf(“\n enter second employee number,
, sex and fees”); name, designation, salary and work
scanf(“%d%s%d\n%c%f”,&stud2.rno, experience”);
stud2.name, &stud2.age, &stud2.sex, scanf(“%d%s%s%f%d”,&e2.empno,
&stud2.fees); e2.ename, e2.designation, &e2.salary,
&e2.experience);
printf(“\n First student details”);
printf(“\n Roll number=%d”,stud1.rno); printf(“\n First employee details”);
printf(“\n Name=%s”,stud1.name); printf(“\n Employee number=%d”,e1.empno);
printf(“\n Age=%d”,stud1.age); printf(“\n Name=%s”,e1.name);
printf(“\n Sex=%c”,stud1.sex); printf(“\n Designation=%s”,e1.designation);
printf(“\n Fees=%f”,stud1.fees); printf(“\n Salary=%f”,e1.salary);
printf(“\n Work Experience=%d”,e1.experience);
printf(“\n Second student details”);
printf(“\n Roll number=%d”,stud2.rno); printf(“\n second employee details”);
printf(“\n Name=%s”,stud2.name); printf(“\n Employee number=%d”,e2.empno);
printf(“\n Age=%d”,stud2.age); printf(“\n Name=%s”,e2.name);
printf(“\n Sex=%c”,stud2.sex); printf(“\n Designation=%s”,e2.designation);
printf(“\n Fees=%f”,stud2.fees); printf(“\n Salary=%f”,e2.salary);
printf(“\n Work Experience=%d”,e2.experience);
printf(“\n Third student details”);
printf(“\n Roll number=%d”,stud3.rno); e3=e2;
printf(“\n Name=%s”,stud3.name); printf(“\n copied employee details”);
printf(“\n Age=%d”,stud3.age); printf(“\n Employee number=%d”,e3.empno);
printf(“\n Sex=%c”,stud3.sex); printf(“\n Name=%s”,e3.name);
printf(“\n Fees=%f”,stud3.fees); printf(“\n Designation=%s”,e3.designation);
printf(“\n Salary=%f”,e3.salary);
} printf(“\n Work Experience=%d”,e3.experience);
}

http://pradeeppearlz.blogspot.com 7 User-Defined Data types


Interview question #5
What are the differences between array and structures?
Array Structure
An array is homogeneous collection of A structure is heterogeneous collection of data
elements stored in contiguous memory items stored in contiguous memory locations
locations referred by common name. referred by common name.
Individual data items in an array are called as Individual data items in a structure are called
elements. as members.
An array declaration reserves enough The creation of structure variables reserves
memory space for its elements. enough memory space for members of
structure.
There is no keyword to represent arrays but The keyword struct tells us that we are
the square brackets[] preceding the variable dealing with the structures.
name tells us that we are dealing with arrays.
Initialization of elements can be done during Initialization of members can be done only
array declaration. after the creation of structure variables.
The general format: The general format:
<data type> <array_name>[size]; struct <tag>
{
Ex: int a[10]; <data type1> <member(s)>;
<data type2> <member(s)>;
:
:
<data typeN> <member(s)>;
};
struct <tag> <var1,var2…varN>;

Ex: struct student


{
int rno,age;
char name[15],sex;
float fees;
};
struct student stud1,stud2;

Array size is known at the time of declaration. The members and their respective data types
are known at the time of declaration.
An array name represents the address of The structure name is not the base address.
starting element (or base address).
The array elements are accessed by its name The members of the structure are accessed by
followed by the square brackets [] within using the dot operator. The following form will
which the index is placed. be helpful to access the members:
Ex: a[3] is used to access the 4th element in <structure_variable>.<member_name>
the array. Ex: stud1.age is used to access the member
age.

An array can not have bit fields. A structure can have bit fields.
http://pradeeppearlz.blogspot.com 8 User-Defined Data types
12.1.3. Structure within a structure (Nested structure)
A structure can also be placed as a member in another structure. This can be done in two ways:
1. Place entire structure declaration along with structure variable in a structure (or)
2. Declare structure individually and place the structure variable in another structure.
The following example demonstrates this:
Method-1 Method-2
struct student //outer structure struct date_of_birth
{ {
int rno,age; int dd,mm,yy;
char name[15],sex; };
float fees; struct student
struct date_of_birth //Inner structure {
{ int rno,age;
int dd,mm,yy; char name[15],sex;
}dob; float fees;
}stud1,stud2; struct date_of_birth dob;
//structure variable of structure date_of_birth
}stud1,stud2;
Once the nested structure is declared, the inner structures become the members of outer structure. By
using the structure variable of outer structure, the inner structures variables get accessed. As dot operator
indicates membership, it should be used in between outer structure variable and inner structure variables
in order to access the members of inner structure.
e.g., In order to access the members of structure date_of_birth, the structure variables dob and stud1 are
used as follows:
stud1.dob.dd=8;
stud1.dob.mm=3;
stud1.dob.yy=1983;
Program #3 Program #4
/* program to read 3 student details and /* program to read 2 Employee details and
print them*/ print them*/
#include<stdio.h> #include<stdio.h>
struct student main()
{ {
int rno,age; struct address
char name[15],sex; {
float fees; char *street,*area,*city;
struct date_of_birth long int pincode;
{ };
int dd,mm,yy; typedef struct employee
}dob; {
}; int empno,experience;
main() float salary;
{ char *ename,*designation;
struct student stud1,stud2; struct address add;
struct student stud3={14,18,”amrutha”, }EMPRECORD;
’f’,27500.00,12,3,1991};
printf(“\n enter first student rno , name , age , EMPRECORD e1,e2,e3;
sex,fees”);
scanf(“%d%s%d\n%c%f”,&stud1.rno, printf(“\n enter first employee number, name,
stud1.name, &stud1.age, &stud1.sex, designation, salary and work experience”);
&stud1.fees); scanf(“%d%s%s%f%d”,&e1.empno,
printf(“\n Enter date-of-birth”); e1.ename, e1.designation, &e1.salary,

http://pradeeppearlz.blogspot.com 9 User-Defined Data types


scanf(“%d%d &e1.experience);
%d”,&stud1.dob.dd,&stud1.dob.mm,&stud1.dob
.yy); printf(“\n Enter address ( street , area , city ,
pincode )”);
printf(“\n enter second student rno , name , scanf(“%s%s%s%ld”,e1.add.street,e1.add.area,
age , sex and fees”); e1.add.city, &e1.add.pincode);
scanf(“%d%s%d\n%c%f”,&stud2.rno,
stud2.name, &stud2.age, &stud2.sex, printf(“\n enter second employee number, name,
&stud2.fees); designation, salary and work experience”);
printf(“\n Enter date-of-birth”); scanf(“%d%s%s%f%d”,&e2.empno, e2.ename,
scanf(“%d%d e2.designation, &e2.salary, &e2.experience);
%d”,&stud2.dob.dd,&stud2.dob.mm,&stud2.dob printf(“\n Enter address ( street , area , city ,
.yy); pincode )”);
scanf(“%s%s%s%ld”,e2.add.street,e2.add.area,
printf(“\n First student details”); e2.add.city, &e2.add.pincode);
printf(“\n Roll number=%d”,stud1.rno);
printf(“\n Name=%s”,stud1.name);
printf(“\n Age=%d”,stud1.age); printf(“\n First employee details”);
printf(“\n Sex=%c”,stud1.sex); printf(“\n Employee number=%d”,e1.empno);
printf(“\n Fees=%f”,stud1.fees); printf(“\n Name=%s”,e1.name);
printf(“\n Date-of-birth = %d / %d / % d ” , printf(“\n Designation=%s”,e1.designation);
stud1.dob.dd, stud1.dob.mm, stud1.dob.yy); printf(“\n Salary=%f”,e1.salary);
printf(“\n Work Experience=%d”,e1.experience);
printf(“\n Second student details”); printf(“\nstreet=%s\nArea=%s\nCity=%s\
printf(“\n Roll number=%d”,stud2.rno); nPincode=
printf(“\n Name=%s”,stud2.name); %ld”,e1.add.street,e1.add.area,e1.add.city,
printf(“\n Age=%d”,stud2.age); e1.add.pincode);
printf(“\n Sex=%c”,stud2.sex);
printf(“\n Fees=%f”,stud2.fees); printf(“\n second employee details”);
printf(“\n Date-of-birth = %d / %d / % d ” , printf(“\n Employee number=%d”,e2.empno);
stud2.dob.dd, stud2.dob.mm, stud2.dob.yy); printf(“\n Name=%s”,e2.name);
printf(“\n Designation=%s”,e2.designation);
printf(“\n Third student details”); printf(“\n Salary=%f”,e2.salary);
printf(“\n Roll number=%d”,stud3.rno); printf(“\n Work Experience=%d”,e2.experience);
printf(“\n Name=%s”,stud3.name); printf(“\nstreet=%s\nArea=%s\nCity=%s\
printf(“\n Age=%d”,stud3.age); nPincode=
printf(“\n Sex=%c”,stud3.sex); %ld”,e2.add.street,e2.add.area,e2.add.city,
printf(“\n Fees=%f”,stud3.fees); e2.add.pincode);
printf(“\n Date-of-birth = %d / %d / % d ” ,
stud3.dob.dd, stud3.dob.mm, stud3.dob.yy);
e3=e2;
}
printf(“\n copied employee details”);
printf(“\n Employee number=%d”,e3.empno);
printf(“\n Name=%s”,e3.name);
printf(“\n Designation=%s”,e3.designation);
printf(“\n Salary=%f”,e3.salary);
printf(“\n Work Experience=%d”,e3.experience);
printf(“\nstreet=%s\nArea=%s\nCity=%s\
nPincode=
%ld”,e3.add.street,e3.add.area,e3.add.city,
e3.add.pincode);
}
Note: A structure can not be nested inside the same structure. For example,
struct student
{ int rno,age;
char name[15],sex;

http://pradeeppearlz.blogspot.com 10 User-Defined Data types


float fees;
struct student stud1; //invalid statement
}; is not a valid nested structure.

http://pradeeppearlz.blogspot.com 11 User-Defined Data types


12.1.4. Arrays and structures
12.1.4.1. Array within a structure
An array can also be placed as a member in the structure declaration. It can be initialized and accessed as
follows:
Ex: /*program to read 3 subjects marks, calculate grade on sum of these marks*/
#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[15],grade[15];
int marks[3]; //array with in a structure
int total;
}stud1;

main()
{
printf(“\n Enter student rno,name”);
scanf(“%d%s”,&stud1.rno,stud1.name);
printf(“\n Enter student 3 subjects marks:”);
for(i=0;i<3;i++)
scanf(“%d”,&stud1.marks[i]);
stud1.total=0;
for(i=0;i<n;i++)
{
printf(“\nSubject%d=%d”,i+1,stud1.marks[i]);
stud1.total+=stud1.marks[i];
}

if(stud1.marks[0]<35 || stud1.marks[1]<35 || stud1.marks[2]<35)


strcpy(stud1.grade,”failed”);
else if(stud1.total>=250)
strcpy(stud1.grade,”First class”);
else if(stud1.total<250 && stud1.total>=150)
strcpy(stud1.grade,”second class”);
else
strcpy(stud1.grade,”Third class”);
printf(“\n %s has got %s”,stud1.name,stud1.grade);
}
12.1.4.2. Array of structures
An array is a collection of elements of same data type that are stored in contiguous memory locations. A
structure is a collection of members of different data types stored in contiguous memory locations. An
array of structures is an array in which each element is a structure. This concept is very helpful in
representing multiple records of a file, where each record is a collection of dissimilar data items.

Ex: An array of structures for structure student can be declared as


struct student s[20];
In this example student[20] is a structure variable. It may contain the details of 20 students. Each record
may be accessed and processed separately like individual elements of an array.

http://pradeeppearlz.blogspot.com 12 User-Defined Data types


Program #5 Program #6
/* program to read multiple student details /* program to read mutliple Employee
and print them*/ details and print them*/
#include<stdio.h> #include<stdio.h>
struct student main()
{ {
int rno,age; struct address
char name[15],sex; {
float fees; char *street,*area,*city;
struct date_of_birth long int pincode;
{ };
int dd,mm,yy; typedef struct employee
}dob; {
}; int empno,experience;
main() float salary;
{ char *ename,*designation;
struct student stud[15]; struct address add;
int i,n; }EMPRECORD;
printf(“\n Howmany records:”);
scanf(“%d”,&n); EMPRECORD e[10];
int i,n;
for(i=0;i<n;i++) printf(“\n Howmany records:”);
{ scanf(“%d”,&n);
printf(“\n enter student %d rno , name , age ,
sex,fees”,i+1); for(i=0;i<n;i++)
scanf(“%d%s%d\n%c%f”,&stud[i].rno, {
stud[i].name, &stud[i].age, &stud[i].sex, printf(“\n enter %d employee number, name,
&stud[i].fees); designation, salary and work experience”,i+1);
printf(“\n Enter date-of-birth”); scanf(“%d%s%s%f%d”,&e[i].empno,
scanf(“%d%d e[i].ename, e[i].designation, &e[i].salary,
%d”,&stud[i].dob.dd,&stud[i].dob.mm,&stud[i]. &e[i].experience);
dob.yy);
} printf(“\n Enter address ( street , area , city ,
printf(“\n======================”); pincode )”);
printf(“\nRno\tName\tAge\tSex\tfees\tdate-of- scanf(“%s%s%s%ld”,e[i].add.street,
birth”); e[i].add.area, e[i].add.city, &e[i].add.pincode);
printf(“\n======================”); }
for(i=0;i<n;i++) printf(“\n======================”);
{ printf(“\nEno\tEName\tdesignation\tsalary\t
printf(“\n%d\t%s\t%d\t%c\t%f\t%d/%d/%d”, experience\t address”);
std[i].rno,stud[i].name,stud[i].age,stud[i].sex, printf(“\n======================”);
stud[i].fees,stud[i].dob.dd,stud[i].dob.mm, for(i=0;i<n;i++){
stud[i].yy); printf(“\n%d\t%s\t%s\t%f\t(%s, %s, %s, %ld)”
} e[i].empno,e[i].ename,e[i].designation,e[i].salar
printf(“\n======================”); y,e[i].experience,e[i].add.street,e[i].add.area,e[i
} ].add.city,e.add.pincode); }
printf(“\n======================”);}

http://pradeeppearlz.blogspot.com 13 User-Defined Data types


12.1.5. Structures and pointers
12.1.5.1. Pointer-to-structure
The members of a structure can not only be accessed with the help of structure variable, but also with a
pointer to a structure. The following example demonstrates this:
Ex: 1. First, create a pointer to the structure as follows:
struct student
{ int rno;
char name[15],sex;
float fees;
struct date_of_birth
{
int dd,mm,yy;
}dob;
};
struct student *stdptr; //pointer to structure

2. Secondly, Initialize that structure pointer with the address of a structure variable.
struct student std1;
stdptr=&std1; //initialization

Point to ponder #4
Pointer-to-structure holds the address of first byte of first member in structure declaration.

3. Finally, access the members of that structure using structure pointer as follows:
Method-1 (by using arrow operator) Method-2 (by using Indirection operator)
stdptr->rno=28 (*stdptr).rno=28
strcpy(stdptr->name,”Harish”); strcpy((*stdptr).name,”Harish”);
stdptr->sex=’m’; (*stdptr).sex=’m’;
stdptr->fees=27500.00; (*stdptr).fees=27500.00;
stdptr->dob.dd=12; (*stdptr).dob.dd=12;
stdptr->dob.mm=03; (*stdptr).dob.mm=03;
stdptr->dob.yy=1991; (*stdptr).dob.yy=1991;

Interview question #6
The way mentioning the array name or function name with out [] or () yields their base
address, what do you obtain on mentioning structure name?
The entire structure itself and not its base address.

http://pradeeppearlz.blogspot.com 14 User-Defined Data types


12.1.5.2. Self-referential structures
Interview question #7
What is a self-referential structure?
Self-referential structure is the structure that contains a pointer that points to the same structure as a
member. E.g., the structure declaration
struct Node
{
int data;
struct Node *next;
};
declares a type struct Node. The type struct Node has two members: data of type int and a pointer
member next. The member next points to a structure of type struct Node- a structure of the same type
as the one being declared here, hence the term “self-referential structure”. The member next is
referred to as a link- i.e., the next can be used to tie a structure of type struct node to another
structure of the same type.
Self-referential structures can be linked together to form useful data structures such as linked
lists, trees, graphs, stacks and queues.

/*A program to create and display the contents of linked list*/


#include<stdio.h>
#include<malloc.h>
struct Node
{ int data;
struct Node *next;
};
main()
{ struct Node *firstnode,*prevnode,*newnode;
int value;
printf(“\n Enter integers (-999 to stop):”);
scanf(“%d”,&value);
firstnode=prevnode=NULL;
while(value!=-999)
{ newnode=(struct Node*) malloc(sizeof(struct Node));
newnode->data=value;
newnode->next=NULL;

if(firstnode==NULL)
firstnode=newnode;
else
prevnode->next=newnode;
prevnode=newnode;
scanf(“%d”,&value);
}
printf(“\n The Linked list:Head->”);
while(firstnode!=NULL)
{ printf(“%d->”,firstnode->data);
firstnode=firstnode->next;
}
printf(“NULL”);
}

http://pradeeppearlz.blogspot.com 15 User-Defined Data types


12.1.5.3. Structure pointer and dynamic memory allocation
Memory is allocated dynamically for structure pointer also same as to integer pointers to hold multiple
values. However, when the memory is allocated, the generic pointer that is returned by malloc() should be
converted to the structure pointer. The following program demonstrates this concept:
/* program to read multiple student details and print them*/
#include<stdio.h>
struct student
{
int rno,age;
char name[15],sex;
float fees;
struct date_of_birth
{
int dd,mm,yy;
}dob;
};
main()
{
struct student *stud;
int i,n;
printf(“\n Howmany records:”);
scanf(“%d”,&n);

for(i=0;i<n;i++)
stud=(struct student *)malloc(n*sizeof(struct student));

for(i=0;i<n;i++)
{
printf(“\n enter student %d rno , name , age , sex,fees”,i+1);
scanf(“%d%s%d\n%c%f”,&stud[i].rno, stud[i].name, &stud[i].age, &stud[i].sex, &stud[i].fees);
printf(“\n Enter date-of-birth”);
scanf(“%d%d%d”,&stud[i].dob.dd,&stud[i].dob.mm,&stud[i].dob.yy);
}
printf(“\n======================================================”);
printf(“\nRno\tName\tAge\tSex\tfees\tdate-of-birth”);
printf(“\n======================================================”);
for(i=0;i<n;i++)
{
printf(“\n%d\t%s\t%d\t%c\t%f\t%d/%d/%d”, std[i].rno,stud[i].name,stud[i].age,stud[i].sex,
stud[i].fees,stud[i].dob.dd,stud[i].dob.mm, stud[i].yy);
}
printf(“\n======================================================”);
}

12.1.5.4. Array of structure pointers and dynamic memory allocation


Memory is allocated dynamically for array of structure pointers also same as to array of integer pointers to
hold multiple values. However, when the memory is allocated, the generic pointer that is returned by
malloc() should be converted to the structure pointer. The following program demonstrates this concept:

http://pradeeppearlz.blogspot.com 16 User-Defined Data types


/* program to sort multiple student details based on rank*/
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
};
void sort(struct student *[],int);
void swap(struct student *,struct student *);
main()
{
struct student *stud[10]; //array of structure pointers
int i,n;
printf(“\n Howmany records:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
stud[i]=(struct student *)malloc(sizeof(struct student); //allocate memory individually
printf(“\n enter student %d rno , name and rank”,i+1);
scanf(“%d%s%d”,&stud[i]->rno,stud[i]->name,&stud[i]->rank);
}
sort(stud,n);
}
void sort(struct student *stud[],int n)
{
for(i=0;i<n;i++)
{ for(j=i+1;j<n;j++)
{ if(stud[i]->rank>=stud[j]->rank)
swap(stud[i],stud[j]);
}
}
}

void swap(struct student *p,struct student *q)


{
struct student temp;
temp=*p;
*p=*q;
*q=temp;
}
12.1.6. Structures and Functions
12.1.6.1. Structure as an argument
A structure can be passed to a function as a single variable. When we pass an entire structure to a
function, we are passing it by call by value method. Because we are working on the copy of the structure,
any changes made to the structure members within the function are not reflected in the original structure.

http://pradeeppearlz.blogspot.com 17 User-Defined Data types


#include<stdio.h>
struct date
{
int day,month,year;
};
void display(struct date);//function prototype
main()
{
struct date today;
today.day=10;
today.month=3;
today.year=2009;
display(today); //function call
}
void display(struct date one) //function defintion
{
printf(“%d\t%d\t%\td”,one.day,one.month,one.year);
}

12.1.6.2. Structure as a return value


When we pass a structure variable as an argument to a function, we are passing it to the called function
by using call-by-value method. Because we are working on the copy of the structure, any changes made
to the structure members within the function are not reflected in the original structure. Hence, it is
necessary for the function to return entire structure back to the calling function. The following program
demonstrates this concept:
/* A menu-driven program to perform various operations on complex numbers*/
#include<stdio.h>
typedef struct complexnumber
{
float real;
float imag;
}COMPLEX;

COMPLEX add(COMPLEX,COMPLEX);
COMPLEX sub(COMPLEX,COMPLEX);
COMPLEX mul(COMPLEX,COMPLEX);
COMPLEX div(COMPLEX,COMPLEX);

main()
{
COMPLEX c1,c2,c3;

printf("\n enter first complex number (real,imaginary):");


scanf("%f%f",&c1.real,&c1.imag);
printf("\n enter second complex number (real,imaginary):");
scanf("%f%f",&c2.real,&c2.imag);
while(1)
{
printf(“\n1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Exit”);
printf(“\n Enter your choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: c3=add(c1,c2);
http://pradeeppearlz.blogspot.com 18 User-Defined Data types
printf("\n Result=%f+%fi",c3.real,c3.imag);
break;
case 2: c3=sub(c1,c2);
printf("\n Result=%f+%fi",c3.real,c3.imag);
break;
case 3: c3=mul(1,c2);
printf("\n Result=%f+%fi",c3.real,c3.imag);
break;
case 4: c3=div(c1,c2);
printf("\n Result=%f+%fi",c3.real,c3.imag);
break;
case 5: exit(0);
default: printf(“\n Wrong choice”);
}
}
}

COMPLEX add(COMPLEX c1,COMPLEX c2)


{
COMPLEX c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c; //returning a structure
}

COMPLEX sub(COMPLEX c1,COMPLEX c2)


{
COMPLEX c;
c.real=c1.real-c2.real;
c.imag=c1.imag-c2.imag;
return c; //returning a structure
}

COMPLEX mul(COMPLEX c1,COMPLEX c2)


{
COMPLEX c;
c.real=(c1.real*c2.real)-(c1.imag*c2.imag);
c.imag=(c1.real*c2.imag)+(c1.imag*c2.real);
return c; //returning a structure
}

COMPLEX div(COMPLEX c1,COMPLEX c2)


{
COMPLEX c;
float temp;
temp=(c2.real*c2.real)+(c2.imag*c2.imag);
c.real=((c1.real*c2.real)+(c1.imag*c2.imag))/temp;
c.imag=((c2.real*c1.imag)-(c1.real*c2.imag))/temp;
return c; //returning a structure
}

http://pradeeppearlz.blogspot.com 19 User-Defined Data types


12.1.6.3. Array of structures as an argument
As an array can be passed as an argument, an array of structures can also be passed as an argument.
Because we are passing the name of the array as an argument and the array name acts as reference, this
method of passing an array argument is the call-by-reference.
/* program to read multiple student details and print them*/
#include<stdio.h>
struct student
{ int rno,age;
char name[15],sex;
float fees;
struct date_of_birth
{
int dd,mm,yy;
}dob;
};
void display(struct student [],int);
main()
{ struct student stud[15];
int i,n;
printf(“\n Howmany records:”);
scanf(“%d”,&n);

for(i=0;i<n;i++)
{ printf(“\n enter student %d rno , name , age , sex,fees”,i+1);
scanf(“%d%s%d\n%c%f”,&stud[i].rno, stud[i].name, &stud[i].age, &stud[i].sex, &stud[i].fees);
printf(“\n Enter date-of-birth”);
scanf(“%d%d%d”,&stud[i].dob.dd,&stud[i].dob.mm,&stud[i].dob.yy);
}
display(stud,n);
}
void display(struct student stud[15],int n)
{ printf(“\n=================================================”);
printf(“\nRno\tName\tAge\tSex\tfees\tdate-of-birth”);
printf(“\n=================================================”);
for(i=0;i<n;i++)
{printf(“\n%d\t%s\t%d\t%c\t%f\t%d/%d/%d”,std[i].rno,stud[i].name,stud[i].age,stud[i].sex,
stud[i].fees, stud[i].dob.dd,stud[i].dob.mm, stud[i].yy);
}
printf(“\n=================================================”);
}

12.1.6.4. Pointer-to-structure as an argument


When we pass a structure variable as an argument to a function, we are passing it to the called function
by using call-by-value method. Because we are working on the copy of the structure, any changes made
to the structure members within the function are not reflected in the original structure. So, to change the
called function’s arguments in called function, we can pass a pointer-to-structure as an argument. The
following program demonstrates this concept:

http://pradeeppearlz.blogspot.com 20 User-Defined Data types


/*program to exchange two numbers /*program to exchange two numbers
(call-by-value)*/ (call-by-reference)*/
struct exchange
{ struct exchange
int a,b; {
}; int a,b;
void swap(struct exchange); //function prototype };
main() void swap(struct exchange*);
{ //function prototype
struct exchange ex; main()
ex.a=20; {
ex.b=10; struct exchange ex;
printf(“\nBefore swap a=%d\tb=%d”,ex.a,ex.b); ex.a=20;
swap(ex); //function call ex.b=10;
printf(“\nAfter swap a=%d\tb=%d”,ex.a,ex.b); printf(“\nBefore swap a=%d\tb=%d”,ex.a,ex.b);
} swap(&ex);
void swap(struct exchange e)//function definition //function call: address as an argument
{ printf(“\nAfter swap a=%d\tb=%d”,ex.a,ex.b);
int temp; }
temp=e.a; //function definition
e.a=e.b; void swap(struct exchange *e)
e.b=temp; {
} int temp;
temp=e->a;
e->a=e->b;
e->b=temp;
}
12.1.6.5. Pointer-to-structure as a return value
Returning pointer-to-structure has the same syntax as returning pointer to ordinary variable. The
following program demonstrates this:
/*program to print the details of highest salary paid employee*/
#include<stdio.h>
main()
{
struct address
{
char *street,*area,*city;
long int pincode;
};
typedef struct employee
{
int empno,experience;
float salary;
char *ename,*designation;
struct address add;
}EMPRECORD;

EMPRECORD *highest(EMPRECORD [],int); //function prototype

EMPRECORD e[10];
EMPRECORD *temp;
int i,n;

http://pradeeppearlz.blogspot.com 21 User-Defined Data types


printf(“\n Howmany records:”);
scanf(“%d”,&n);

for(i=0;i<n;i++)
{
printf(“\n enter %d employee number, name, designation, salary and work
experience”,i+1);
scanf(“%d%s%s%f%d”,&e[i].empno, e[i].ename, e[i].designation, &e[i].salary,
&e[i].experience);

printf(“\n Enter address ( street , area , city , pincode )”);


scanf(“%s%s%s%ld”,e[i].add.street, e[i].add.area, e[i].add.city, &e[i].add.pincode);
}
temp=highest(e,n);
printf(“\n Highest salary paid employee details\n”);
printf(“\n Name=%s”,temp->ename);
printf(“\n Designation=%s”,temp->designation);
printf(“\n Salary=%.2f”,temp->salary);
}

EMPRECORD *highest(EMPRECORD e[],int n)


{
float s;
int pos;
s=e[0].salary;
for(i=1;i<n;i++)
{
if(s<e[i].salary)
pos=i;
}
return (&e[pos]); //returns pointer-to-structure
}

Programming Examples
1) /*A menu-driven program to process student records (using array of structures)*/
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
struct date_of_birth
{
int day,month,year;
}dob;
};
void display(struct student[],int);
void insert(struct student[],int);
void delete(struct student[],int);
void search(struct student[],int);
main()
{
int n,i,ch;
struct student stud[10];
printf("\n Enter how many students:");
scanf("%d",&n);
for(i=0;i<n;i++)
http://pradeeppearlz.blogspot.com 22 User-Defined Data types
{
printf("\n Enter student %d details",i+1);
printf("\n Enter roll number:");
scanf("%d",&stud[i].rno);
printf("\n Enter name:");
scanf("%s",stud[i].name);
printf("\n Enter rank:");
scanf("%d",&stud[i].rank);
printf("\n Enter date of birth(day,month,year):");
scanf("%d%d%d",&stud[i].dob.day,&stud[i].dob.month,&stud[i].dob.year);
}
while(1)
{
printf("\n1.Print\n2.Insert\n3.Delete\n4.Search\n5.Exit");
printf("\n Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: display(stud,n);
break;
case 2: insert(stud,n);
break;
case 3: delete(stud,n);
break;
case 4: search(stud,n);
break;
case 5: exit(0);
default: printf("\n Wrong choice");
}
}
}
void display(struct student s[],int n)
{
int i;
printf("\n Student details");
for(i=0;i<n;i++)
{
printf("\n%d\t%s\t%d\t%d/%d/%d",s[i].rno,s[i].name,s[i].rank,s[i].dob.day,s[i].dob.month,
s[i].dob.year);
}

}
void insert(struct student s[],int n)
{
struct student new;
int pos,i;
printf("\n Enter new student details(rno,name,rank and date of birth):");
scanf("%d%s%d%d%d%d",&new.rno,new.name,&new.rank,&new.dob.day,&new.dob.month,
&new.dob.year);
printf("\n Enter the position:");
scanf("%d",&pos);
for(n++,i=n-1;i>pos-1;i--)
s[i]=s[i-1];
s[pos-1]=new;
display(s,n);
}
void delete(struct student s[],int n)
{
http://pradeeppearlz.blogspot.com 23 User-Defined Data types
int pos,i;
printf("\n Enter the position:");
scanf("%d",&pos);
for(i=pos-1;i<n;i++)
s[i]=s[i+1];
display(s,n);
}
void search(struct student s[],int n)
{
int rollnum,flag=0,pos,i;
printf("\n Enter the roll number to be searched:");
scanf("%d",&rollnum);
for(i=0;i<n;i++)
{
if(s[i].rno==rollnum)
{
pos=i;
flag=1;
break;
}
}
if(flag==1)
{
printf("\n The student details are:");
printf("%d\t%s\t%d\t%d/%d/%d",s[pos].rno,s[pos].name,s[pos].rank,s[pos].dob.day,
s[pos].dob.month,s[pos].dob.year);
}
else
printf("\n The record is not found");
}
2) /* A program to add two matrices using structures*/
#include<stdio.h>
typedef struct
{
int **data;
int row,col;
}matrix;
main()
{
matrix m1,m2,m3;
int i,j;
printf("\n Enter first matrix order:");
scanf("%d%d",&m1.row,&m1.col);
printf("\n Enter second matrix order:");
scanf("%d%d",&m2.row,&m2.col);
if(m1.row!=m2.row||m1.col!=m2.col)
printf("\n Sorry, addition is not possible");
else
{
m1.data=(int **)malloc(m1.row*sizeof(int));
for(i=0;i<m1.row;i++)
m1.data[i]=(int *)malloc(m1.col*sizeof(int));

printf("\n Enter first matrix elements:");


for(i=0;i<m1.row;i++)
for(j=0;j<m1.col;j++)
scanf("%d",&m1.data[i][j]);
http://pradeeppearlz.blogspot.com 24 User-Defined Data types
m2.data=(int **)malloc(m2.row*sizeof(int));
for(i=0;i<m1.row;i++)
m2.data[i]=(int *)malloc(m2.col*sizeof(int));

printf("\n Enter second matrix elements:");


for(i=0;i<m2.row;i++)
for(j=0;j<m2.col;j++)
scanf("%d",&m2.data[i][j]);

m3.row=m1.row;
m3.col=m1.col;

m3.data=(int **)malloc(m3.row*sizeof(int));
for(i=0;i<m3.row;i++)
m3.data[i]=(int *)malloc(m3.col*sizeof(int));

printf("\n Resultant matrix:\n");


for(i=0;i<m3.row;i++)
{
for(j=0;j<m3.col;j++)
{
m3.data[i][j]=m1.data[i][j]+m2.data[i][j];
printf("%d\t",m3.data[i][j]);
}
printf("\n");
}
}
}

12.2.1. Unions

Interview question #8
What is a union?
Union is also a user-defined data type like a structure, except that it provides a way to manipulate
different kinds of data in a single area of storage.
For different situations in a program, some variables may not be relevant, but other variables
are- so a union shares the space instead of wasting storage on variables that are not being used. The
members of a union can be of any data type. The number of bytes used to store a union must be at
least enough to hold the largest member. In most cases, unions contain two or more data types. Only
one member, and thus one data type, can be referenced at a time.

http://pradeeppearlz.blogspot.com 25 User-Defined Data types


12.2.1. Working with unions
In order to work with a union, one should do these things:
 Declare its prototype.
 Create variable(s) of that union.
 Access the members of that union.

12.2.1.1. Declaring a union


A union is declared same as a structure is declared except the keyword union. A union is declared as
follows:
union <tag>
{
<data type1> <member(s)>;
<data type2> <member(s)>;
:
:
<data typeN> <member(s)>;
};
In this syntax,
 union is the keyword. <tag>, an optional one, serves as a name for this union. It is used to
declare variable of the same union type. It should be a valid identifier. The first line of this
declaration is called as union header.
 All the members of the union should be enclosed in curly braces. These members may be variables,
constants, arrays, pointers and so on. If there are more members of same type, those should be
separated with commas. All the declarations in the curly braces collectively referred to as union
body.
It is important to note that the union declaration should be ended with a semi colon. The union name or
members of union may be omitted, but both, should not be omitted.
Ex: union student
{
int rno,age;
char name[15],sex;
float fees;
};
In this example, the union student consists of the members: rno and age as integers, name and sex as of
char type and fees as of type float.

12.2.1.2. Creating a union variable


A union variable is created same as a structure variable is created. After the declaration of union, a
variable of that type of union should be created in order to access the members of union. The creation of
variable takes the following form:

union <tag> <var1,var2…varN>;

http://pradeeppearlz.blogspot.com 26 User-Defined Data types


In this syntax,
union is the keyword. <tag> is the name of the union. <var1, var2 … varN> should be valid identifiers.
Ex: union student s1,s2;
The above statement defines two union variables of type student: s1, s2. Usually, this statement can be
placed in body of main().

12.2.1.3. Accessing the members of a union


Just like in a structure, the membership operator or dot is used in between union variable and member of
union in order to access the member of union.
Ex: union student
{
int rno,age;
char name[15],sex;
float fees;
}s1;
In order to access the member fees of this union, we should use this statement: s1.fees

12.2.2. Properties of union

1) Initialization
Though we can initialize all the members of a union at a time, only one member is always active.
Because all the members share the same memory location, the value of one member overwrites
the value of other member that is there in memory. The following program demonstrates this:
#include<stdio.h>
main()
{
union student
{
int rno,age;
char name[15],sex;
float fees;
}s1;
s1.rno=6;
strcpy(s1.name,”Divya”);
s1.age=18;
s1.sex=’f’;
s1.fees=27500.00;
printf(“%d\t%s\t%d\t%c\t%f”,s1.rno,s1.name,s1.age,s1.sex,s1.fees);
}
Output: only the value of fees gets printed properly. All others are garbage values and zeros.

http://pradeeppearlz.blogspot.com 27 User-Defined Data types


2) Size of a union
The size of a union is always the size of the largest member in that. The following program
demonstrates this:
#include<stdio.h>
main()
{
union student
{
int rno,age;
char name[15],sex;
float fees;
}s1;
printf(“\nsizeof union=%d bytes”,sizeof(s1));
}
Output: sizeof union=15 bytes
Note:
1) A union can also be placed as a member in a structure. How ever, it should be placed after all the
members of structure are declared.
2) A pointer to a union can also be declared. All the members of a union can also be accessed by
using pointer with the help of -> operator.
3) Union can also be initialized when the union variable is declared. But, unlike structures, it can be
initialized only with a value of the same type as the first member. E.g.,
union item
{
int itemno;
float price;
int qty;
};
union item i1={23}; is valid. But, the declaration
union item i1={235.46} is not valid.

Interview question #9
Can a union be self-referenced?
No, a union can not be self-referenced. How ever, a union can contain a pointer to that union as a
member in it. Hence, the following declaration is perfectly valid:
union list
{
long int data;
union list *next;
};
For the above union type, only 8 bytes of memory will be allocated. These 8 bytes of memory can
be shared by both data and pointer next one after other. Hence, there are chances that the values
of these members can overlap each other which lead to data corruption.

http://pradeeppearlz.blogspot.com 28 User-Defined Data types


Interview question #10
What are the differences between structures and unions?
Structure Union
Each member in a structure occupies and uses All the members of a union use the same
its own memory space. memory space.
The keyword struct tells us that we are The keyword union tells us that we are
dealing with structures. dealing with unions.
More memory space is required since each Less memory space is required since all
member is stored in a separate memory members share the same memory location.
location.
The general format: The general format:
struct <tag> union <tag>
{ {
<data type1> <member(s)>; <data type1> <member(s)>;
<data type2> <member(s)>; <data type2> <member(s)>;
: :
: :
<data typeN> <member(s)>; <data typeN> <member(s)>;
}; };
struct <tag> <var1,var2…varN>; union <tag> <var1,var2…varN>;

Ex: struct student Ex: union student


{ {
int rno,age; int rno,age;
char name[15],sex; char name[15],sex;
float fees; float fees;
}; };
struct student stud1,stud2; union student stud1,stud2;

All the members of a structure can be Only first member of union can be initialized.
initialized. e.g., union student stud1 = {46,18,”ravi
kumar”,’m’,27500.00}; is invalid.
e.g., struct student stud1 = {46,18,”ravi
But, union student stud1={46}; is valid.
kumar”,’m’,27500.00};
Any member can be accessed at any time with Since only one member can be handled at a
out loss of data. time, care should be taken to retrieve the data
type from the union variable as the type most
recently used.
Different interpretations for the same memory Different interpretations for the same memory
location are not possible. location are possible.

http://pradeeppearlz.blogspot.com 29 User-Defined Data types


12.3. Enumerated data type
Interview question #11
What is an enumerated data type?
An enumerated data type is a set of values represented by identifiers called enumerators. The
values of each enumerator can be specified when the type is specified. An enumerated data type
is declared as follows:
enum <tag> {<enumerator-1>,<enumerator-2>,<enumerator-3>,…,<enumerator-n>};
In this syntax,
enum is the keyword. <tag> is the name of the enumerated data type.
<enumerator-1>,<enumerator-2>…<enumerator-n> are valid identifiers. All the enumerators
should be separated with commas and enclosed in curly braces.
Ex: enum color{red,green,blue};

Once the enumerators are declared in an enumerated data type, each enumerator holds an integer
constant. Usually, these constant start from 0. So, from the above example, it is clear that the
enumerators hold these constants: red=0, green=1, blue=2
#include<stdio.h>
main()
{
enum color{red,green,blue};
printf(“Red=%d\tGreen=%d\tBlue=%d”,red,green,blue);
}
Output: Red=0 Green=1 Blue=2

We can also specify our own integer constants to enumerators as follows:


#include<stdio.h> #include<stdio.h>
main() main()
{ {
enum color{red,green=234,blue}; enum color{red=12,green=234,blue=423};
printf(“Red=%d\nGreen=%d\nBlue=%d”, printf(“Red=%d\nGreen=%d\nBlue=%d”,red,green,blue);
red,green,blue); }
} Output: Red=12
Output: Red=0 Green=234
Green=234 Blue=423
Blue=235

Note: we can assign enumerators to the variables of enumerated data type and variables of int type also
as follows:
enum day
{sun,mon,tue,wed,thu,fri,sat
} day1,day2;
day1=wed; // day1 holds the value of enumerator-wed. i.e., day1=3
day2=sat; // day2 holds the value of enumerator- sat. i.e., day2=6
int val=wed; // val holds the value of enumerator-wed. i.e., val=3
http://pradeeppearlz.blogspot.com 30 User-Defined Data types
Point to ponder #4
The values of enumerators are fixed; they can never be changed throughout program. When assigned
to a variable, the value in variable can be changed. But that change won’t affect enumerator.

Interview question #12


What are the differences among these?
#define I 20
const int I=20;
enum val{I=20};
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic
constant style of #define. These advantages include a lower maintenance requirement, improved
program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the compiler.
Conversely, symbolic constants must be manually assigned values by the programmer.
2) Another advantage of using the enumeration constant method is that our programs are more
readable and thus can be understood better by others who might have to update our program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can print the
value of an enumeration constant. Conversely, most symbolic debuggers cannot print the value of a
symbolic constant. This can be an enormous help in debugging our program, because if our program is
stopped at a line that uses an enum, we can simply inspect that constant and instantly know its value.
On the other hand, because most debuggers cannot print #define values, we would most likely have to
search for that value by manually looking it up in a header file.

12.4. Bitfields
If a variable in a program takes only one of two values: 0 or 1, we really need a single bit to store it.
Similarly, if a variable is to take values from 0 to 3, then two bits are sufficient to store these values. And
if a variable is to take values from 0 through 7, then three bits will be enough, and so on.
Why do we waste an entire integer (16 bits) when one or two or three bits are sufficient for a variable
to take a value? Well, C provides a concept, i.e., bit field that is used to pack a value in a less number of
bits.

http://pradeeppearlz.blogspot.com 31 User-Defined Data types


Interview question #13
What is a bit field?
C enables programmers to specify the number of bits in which an unsigned or int member of a
structure or union is stored. This is referred to as a bit field. Bit fields enable better memory utilization
by storing data in the minimum number of bits required. Bit field members must be declared as int or
unsigned.
Ex: struct employee
{
unsigned gender:1;
unsigned mar_status:2;
};
The colon in the above declaration tells the compiler that we are talking about bit fields and the number
after it tells how many bits to allot for the field. Once we have established a bit field, we can refer to it
just like other structure member.

Ex: # define MALE 0


# define FEMALE 1
# define SINGLE 0
# define MARRIED 1
# define DIVORCED 2
# define WIDOWED 3
struct employee
{
char *name;
unsigned gender:1;
int mar_status:2;
float salary;
}emp1;
main()
{
emp1.name=”Divyasree”;
emp1.gender=FEMALE;
emp1.mar_status=SINGLE;
emp1.salary=25000.00;
printf(“\n Name=%s”,emp1.name);
printf(“\n gender=%d”,emp1.gender);
printf(“\n Marital status=%d”,emp1.mar_status);
printf(“\n Salary=%f”,emp1.salary);
}

The following are the limitations of bit fields:


 Bit fields do not have addresses.
 Bit fields can not be read using scanf() function.
 Bit fields can not be accessed using pointer.
 Bit fields can not store the values beyond their limits. If larger values are assigned, the output is
undefined.
 Programs written using bit fields are not portable because of the implementation defined nature of
bit fields.

http://pradeeppearlz.blogspot.com 32 User-Defined Data types

You might also like