KEMBAR78
12 User Defined Data Structure and Union | PDF | Pointer (Computer Programming) | Data Type
0% found this document useful (0 votes)
19 views84 pages

12 User Defined Data Structure and Union

The document provides an overview of user-defined data types in C, focusing on structures, unions, and enumerations. It covers how to declare, initialize, access, and manipulate structures, including nested structures and arrays of structures. Additionally, it explains pointers to structures and the copying and comparing of structure variables.

Uploaded by

dakshdhingra260
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views84 pages

12 User Defined Data Structure and Union

The document provides an overview of user-defined data types in C, focusing on structures, unions, and enumerations. It covers how to declare, initialize, access, and manipulate structures, including nested structures and arrays of structures. Additionally, it explains pointers to structures and the copying and comparing of structure variables.

Uploaded by

dakshdhingra260
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

User-defined Data

Types & Variables

© Oxford University Press 2013. All rights reserved.


Objective
 Learn about the user-defined data type called
structure and its tag, members, and variables
 Access, initialize, and copy structures and their
members
 Understand nesting of structures
 Make and initialize arrays of structures
 Comprehend pointer to structures
 Use structures as function arguments and return
values
 Learn about union data types
 Understand enumeration data types
 Get acquainted with bit fields

© Oxford University Press 2013. All rights reserved.


Key Words
 Accessing a structure member : The act of
handling any member of a structure for the purpose
of assigning a value or using the member in any
expression.

 Arrays of structures : It refers to the “structure


variable” when it is an array of objects, each of which
contains the member elements declared within the
structure construct.

 Instance variable : One of the named pieces of


data that make up a structure.
© Oxford University Press 2013. All rights reserved.
Key Words
 Non-homogeneous data: Data of different types such
as integer, float, character, etc.

 Structure: A collection of data grouped together and


treated as a single object.

 Type template: A document or file having a preset


format, used as a starting point for a particular
application so that the format does not have to be
recreated each time it is used.

 Initialization
of structure : Assigning values to
members of an instance variable.
© Oxford University Press 2013. All rights reserved.
Introduction
 C provides facilities to construct user-defined data types
from the fundamental data types.
 A user-defined data type may also be called a derived
data type.
◦ The array type is a derived data type that contains only one
kind of fundamental data types defined in C.

 Such non homogeneous data cannot be grouped to form


an array.
 C provides features to pack heterogeneous data in one
group, bearing a user-defined data type name, and
forming a conglomerate data type called the ‘ structure’
that is capable of holding data of existing type.

© Oxford University Press 2013. All rights reserved.


Check this one
Employee record
Name (string)
Age (int)
Salary (float)
Structure
A structure is a collection of variables
under a single name.
 These variables can be of different
Employee
types, and each has a name that is used record
to select it from the structure.
 There can be structures within structures,  Name
which is known as nesting of structures.  Age
 Arrays of structures can be formed and  Salary

initialized as required. Pointers may also


be used with structures.
 Structures may be passed as function
arguments and they may also be
returned by functions.
© Oxford University Press 2013. All rights reserved.
Declaring Structures & Structure
Variables
A structure is declared by using the
 keyword struct
 followed by an optional structure tag
 by the body of the structure.
◦ The variables or members of the structure
are declared within the body.

© Oxford University Press 2013. All rights reserved.


Structure Declaration
Declaring Structures &
Structure Variables
 A structure can be defined as a user-defined
data type that is capable of holding
heterogeneous data of basic data type.
 The structure is simply a type template with
no associate storage.
 The proper place for structure declarations is in
the global area of the program before main().
 It is not possible to compare structures for
equality using ‘==’, nor is it possible to perform
arithmetic on structures.

© Oxford University Press 2013. All rights reserved.


Declaring Structures &
Structure Variables
 Thestructure_tag_name is the name of the
structure. The structure_variables are the list of
variable names separated by commas.

 There are three different ways to declare and/or define


a structure. These are
◦ Variable structure
◦ Tagged structure
◦ Type-defined structure
Declaring structure
struct [structure tag] {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

 member definition is a normal variable definition, such as


int i; or float f; or any other valid variable definition.
 This creates a structure variable named 's1' and has
separate instance of all members (a, b, c) in the structure
'myStruct'.
Accessing the Members of a
Structure
 The members of a structure can be accessed using the ‘dot
operator’ or member access operator

 The general form of the statement for accessing a member


of a structure is as follows:
< structure_variable >.< member_name > ;

© Oxford University Press 2013. All rights reserved.


output
EXAMPLE-1
Age : 22
Id Number : 1234
struct EmpDatabase {
Salary : 12000.210000
int id_number;
int age;
float salary;
};
int main()
{
struct EmpDatabase employee; /* There is now an employee
variable that has modifiable variables inside it.*/
employee.age = 22;
employee.id_number = 1234;
employee.salary = 12000.21;

printf( "Age : %d\n", employee.age );


printf( "Id Number : %d\n",employee.id_number);
printf( "Salary : %s\n", employee.salary);
}
output
EXAMPLE-2
Age : 22
Id Number : 1234
struct EmpDatabase {
Salary : 12000.210000
int id_number;
int age;
float salary;
}employee; // employee is declared here

int main()
{
employee.age = 22;
employee.id_number = 1234;
employee.salary = 12000.21;

printf( "Age : %d\n", employee.age );


printf( "Id Number : %d\n",employee.id_number);
printf( "Salary : %f\n", employee.salary);
}
EXAMPLE-3 output

struct EmpDatabase { ???


int id_number;
int age;
float salary;
}emp; // emp is declared here

int main()
{
employee.age = 22;
employee.id_number = 1234;
employee.salary = 12000.21;

printf( "Age : %d\n", employee.age );


printf( "Id Number : %s\n",employee.id_number);
printf( "Salary : %s\n", employee.salary);
}
EXAMPLE-4 output

struct EmpDatabase { ???


int id_number;
int age;
float salary;
}emp, employee; // emp is declared here

int main()
{
employee.age = 22;
employee.id_number = 1234;
employee.salary = 12000.21;

printf( "Age : %d\n", emp.age );


printf( "Id Number : %s\n",emp.id_number);
printf( "Salary : %s\n", emp.salary);
}
Initialization of Structures
 Structures that are not explicitly initialized by the
programmer are, by default, initialized by the
system.
 In most of the C compilers, for integer and float
data type members, the default value is zero .
 For char and string type members the default
value is ‘\0’.

© Oxford University Press 2013. All rights reserved.


Initialization of Structures
Way 1 : Declare and Initialize

struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
Initialization of Structures
Way 2 : Declaring and Initializing Multiple
Variables

struct student
{
char name[20];
int roll;
float marks;
}
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
Initialization of Structures
Way 3 : Initializing inside main
struct student
{
char name[20];
int roll;
float marks;
}
void main()
{
struct student s1 = { "Pritesh",67,78.3 };
- - - - --
};
/* print Book1 info */
Two instances of a
printf( "Book 1 title : %s\n", Book1.title);
structure type
printf( "Book 1 book_id : %d\n",
template
Book1.book_id);

#include <stdio.h> /* print Book2 info */


#include <string.h> printf( "Book 2 title : %s\n", Book2.title);
struct Books { printf( "Book 2 book_id : %d\n",
char title[50]; Book2.book_id);
int book_id; return 0;
}; }
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");
Book1.book_id = 6495407; Book 1 title :C Programming
Book 1 book_id: 6495407
/* book 2 specification */ Book 2 title: TelecomBilling
strcpy( Book2.title, "TelecomBilling"); Book 1 book_id :6495700
Book2.book_id = 6495700;
Copying & Comparing Structures
COPY
 A structure can be assigned to another structure
of the same type.
 Here is an example of assigning one structure to
another.
 Corresponding members of one structure variable
get copied to those of another structure variable,
provided they belong to the same structure type.

© Oxford University Press 2013. All rights reserved.


Copying & Comparing Structures
Comparison
 Comparing one structure variable with
another is not allowed in C.
 However, when comparing two structures,
one should compare the individual fields
in the structure.
int number;

int main()
{ char name[20];
int x;
struct structclass student1 = {111,"Rao",72.50};
struct structclass student2 = {222,"Reddy", 67.00}; float marks;
struct structclass student3;

student3 = student2; };

x = ((student3.number == student2.number) &&


(student3.marks == student2.marks)) ? 1 : 0;

if(x == 1)
{
printf("\nstudent2 and student3 are same\n\n");
printf("%d %s %f\n", student3.number,
student3.name,
student3.marks);
} student2 and student3 are
same
else
printf("\nstudent2 and student3 are different\n\n");
return 0; 222 Reddy 67.000000
}
WAP to store one student’s information (i.e. student’s roll no, name,
gender, marks etc) of an
educational institute and display all the data, using structure

#include <stdio.h> printf("\nGender: ");


#include <string.h> scanf("%c", &s.gender);
struct student printf("\nMarks: ");
{ scanf("%f", &s.marks);
int roll; printf("\nThe students details are\n");
char name[25]; printf("\nRoll number: %d",s.roll);
char gender; printf("\nName:%s ", s.name);
float marks; printf("\nGender:%c ", s.gender);
}; printf("\nMarks: %.2f", s.marks);
int main() return 0;
{ }
struct student s;
printf("\nEnter the students data:\n");
printf("\nRoll Number: ");
scanf("%d", &s.roll);
printf("\nName: ");
gets(s.name);
Pointer to structure
 Address of Pointer variable can be obtained using ‘&’
operator.
 Address of such Structure can be assigned to the Pointer
variable .
 Pointer Variable which stores the address of Structure must
be declared as Pointer to Structure .
 Whenever we declare pointer variable ,address of the
structure variable is assigned to the pointer variable.
Pointer to structure
struct student_database
{
char name[10];
int roll;
int marks;
}stud1;
struct student_database *ptr;
ptr = &stud1;

ptr to structure
Pointer to structure
#include <stdio.h>
Access members through dot
int main(int argc, char *argv[])
operator
{

struct student_database {
char name[10];
int roll;
int marks;
}stud1 = {"Pritesh",90,90};
int a=10;
struct student_database *ptr; int *p;
ptr = &stud1; *p=&a;

printf("Roll Number : %d",(*ptr).roll);


printf("Marks of Student : %d",(*ptr).marks);

return 0; OUTPUT
} Roll Number : 90
Marks of Student : 90
Pointer to structure
#include <stdio.h> Access members through
int main(int argc, char *argv[]) membership operator
{

struct student_database {
char name[10];
int roll;
int marks;
}stud1 = {"Pritesh",90,90};

struct student_database *ptr;


ptr = &stud1;

printf("Roll Number : %d",(ptr)->roll); member


printf("Marks of Student : %d",(ptr)->marks); operator

return 0;
} OUTPUT
Roll Number : 90
Marks of Student : 90
Arrays of Structures
 The structure variable would be an array of objects, each of
which contains the member elements declared within the
structure construct.

 The general construct for declaration of an array structure is


given as follows:
struct <structure_tag_name >
{
<data_type member_name1>;
<data_type member_name2>;
.. .
}<structure_variable>[index];
Or
struct <structure_tag_name> <structure_variable>[index];

© Oxford University Press 2013. All rights reserved.


Example: Arrays of Structures

© Oxford University Press 2013. All rights reserved.


Initializing Arrays of
Structures
 Initializing arrays of structures is carried out in
much the same way as arrays of standard data
types.
◦ A typical construct for initialization of an array
of structures would appear as follows:

© Oxford University Press 2013. All rights reserved.


Way1 : Initializing After Declaring
Structure Array :
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {
{"Let us C",700,"YPK",300.00},
{"Wings of Fire",500,"APJ Abdul
Kalam",350.00},
{"Complete C",1200,"Herbt Schildt",450.00}
};
Way 2 : Initializing in Main
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
};
void main()
{
struct Book b1[3] = {
{"Let us C",700,"YPK",300.00},
{"Wings of Fire",500,"Abdul Kalam",350.00},
{"Complete C",1200,"Herbt Schildt",450.00}
};
}
Store student's information
and display using structure
Arrays of Structure
Arrays within the Structure
 An innermost member in a nested structure can be
accessed by chaining all the concerned structure variables,
from outermost to innermost, with the member using the
dot operator.

© Oxford University Press 2013. All rights reserved.


WAP to add two distances (in
inch-feet) using structures.
#include <stdio.h>
struct Distance
//addition
{
int feet; d.feet = d1.feet+d2.feet;
float inch; d.inch = d1.inch+d2.inch;
};
int main() /*If inch is greater than 12,
{ changing it to feet*/
struct Distance d1, d2, d;
if (d.inch>12.0)
printf("\nEnter data for 1st distance\n");
{
printf("\nEnter feet: "); d.inch = d.inch-12.0;
scanf("%d", &d1.feet); ++d.feet;
printf("\nEnter inch: "); }
scanf("%f", &d1.inch);
printf("\nEnter data for 2nd distance\n"); printf("\nSum of distances =
printf("\nEnter feet: "); %d\'-%.1f\"", d.feet, d.inch);
scanf("%d", &d2.feet);
return 0;
printf("\nEnter inch: ");
scanf("%f", &d2.inch);
}
#include <stdio.h>
struct TIME Calculate Difference Between Two
{ Time Periods
int seconds;
int minutes;
int hours;
};
void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct
TIME *diff);

int main()
{
struct TIME startTime, stopTime, diff;

printf("Enter start time: \n");


printf("Enter hours, minutes and seconds respectively: ");
scanf("%d %d %d", &startTime.hours, &startTime.minutes,
&startTime.seconds);

printf("Enter stop time: \n");


printf("Enter hours, minutes and seconds respectively: ");
scanf("%d %d %d", &stopTime.hours, &stopTime.minutes,
&stopTime.seconds);
// Calculate the difference between the start and stop time period.
differenceBetweenTimePeriod(startTime, stopTime, &diff);
printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours,
startTime.minutes, startTime.seconds);
printf("%d:%d:%d ", stopTime.hours, stopTime.minutes,
stopTime.seconds);
printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);

return 0;
}// Now function code
void differenceBetweenTimePeriod(struct TIME start, struct TIME stop,
struct TIME *diff)
{
if(stop.seconds > start.seconds){
--start.minutes;
start.seconds += 60;
}

diff->seconds = start.seconds - stop.seconds;


if(stop.minutes > start.minutes){
--start.hours;
start.minutes += 60;
}

diff->minutes = start.minutes - stop.minutes;


diff->hours = start.hours - stop.hours;
}
OUTPUT

Enter start time:


Enter hours, minutes and seconds respectively: 12
34
55
Enter stop time:
Enter hours, minutes and seconds respectively:8
12
15

TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40


sort array of structure
Define a structure, student, to store the following data about
a student: rollno (integer), name (string) and marks(integer)
Suppose that the class has 20 students. Use an array of 20
elements of type Student. Your program must contain the
following functions:

1. A function to read the students’ data into the array.


2. A function to display records of each student.
3. A function to sort the records of student on the basis of
marks in descending order.
#include <stdio.h>
struct student
{
int rollno;
char name[80];
Sort student's record on marks
int marks;
};
void accept(struct student list[], int s);
void display(struct student list[], int s);
void bsortDesc(struct student list[], int s);

int main()
{
struct student data[20];
int n;

printf("Number of records you want to enter? : ");


scanf("%d", &n);
accept(data, n);

printf("\nBefore sorting");
display(data, n);

bsortDesc(data, n);
printf("\nAfter sorting");
display(data, n);
return 0;
}
void accept(struct student list[80], int s)
{
int i;
for (i = 0; i < s; i++)
{
printf("\n\nEnter data for Record #%d", i + 1);

printf("\nEnter rollno : ");


scanf("%d", &list[i].rollno);

printf("Enter name : ");


gets(list[i].name);

printf("Enter marks : ");


scanf("%d", &list[i].marks);
}
}

void display(struct student list[80], int s)


{
int i;

printf("\n\nRollno\tName\tMarks\n");
for (i = 0; i < s; i++)
{
printf("%d\t%s\t%d\n", list[i].rollno, list[i].name, list[i].marks);
}
}
Number of records you want to
enter? : 3
void bsortDesc(struct student list[80], int s)
{ Enter data for Record #1
Enter rollno : 100
int i, j;
Enter name : Alex
struct student temp; Enter marks : 75

for (i = 0; i < s - 1; i++) Enter data for Record #2


{ Enter rollno : 101
for (j = 0; j < (s - 1-i); j++) Enter name : Vinay
{ Enter marks : 94
if (list[j].marks < list[j + 1].marks)
Enter data for Record #3
{ Enter rollno : 102
temp = list[j]; Enter name : Javed
list[j] = list[j + 1]; Enter marks : 56
list[j + 1] = temp;
} Before sorting
}
Rollno Name Marks
}
100 Alex 75
} 101 Vinay 94
102 Javed 56

After sorting

Rollno Name Marks


101 Vinay 94
100 Alex 75
102 Javed 56
self referential structure
 A self referential data structure is essentially a structure
definition which includes at least one member that is a
pointer to the structure of its own kind.
struct NODE
{
struct NODE new; /* 'new' declared variable */
int value;
};
Self-referential structures have their applications in Advanced
Data Structures like, Linked Lists, Binary Trees etc.
Typedef & its Use in Structure
Declarations
 typedef is a reserved keyword in the C and C++
programming languages. It is used to create an alias name
for another data type
 The typedef keyword allows the programmer to create a
new data type name for an existing data type.
 The general form of the declaration statement using the
typedef keyword is given as follows.
typedef <existing data type> <new data type ,….>;
 The typedef statement does not occupy storage; it simply
defines a new type.
 typedef statements can be placed anywhere in a C
program as long as they come prior to their first use in
the code.

© Oxford University Press 2013. All rights reserved.


Example of Typedef
#include <stdio.h>
// After this line BYTE can be used
// in place of unsifned char
typedef unsigned char BYTE;
int main()
{
BYTE b1, b2;
b1 = 'c';
printf("%c ", b1);
return 0;
} Output :
c
Application of typedef
typedef can be used to give a name to user defined data
type as well. Lets see its use with structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;

Here type_name represents the stucture definition associated


with it. Now this type_name can be used to declare a variable
of this stucture type.
type_name t1, t2 ;
Now access as
thing[i].quantity
thing[i].price
Application of typedef
 In Pointers * binds to the right and not the left.
int* x, y ;

 By this declaration statement, we are actually declaring x


as a pointer of type int, whereas y will be declared as a
plain integer.
typedef int* IntPtr ;
IntPtr x, y, z;
 But if we use typedef like in above example, we can
declare any number of pointers in a single statement.

Summary
•Typedefs can make your code more clear
•Typedefs can make your code easier to modify
Nesting of Structures
 A structure can be placed within another structure.

◦ In other words, structures can contain other structures as


members.
◦ A structure within a structure means nesting of structures.

 In such cases, the dot operator in conjunction with the


structure variables are used to access the members of the
innermost as well as the outermost structures.

◦ It must be noted that an innermost member in a nested


structure can be accessed by chaining all the concerned
structure variables, from outermost to innermost, with the
member using the dot operator.

© Oxford University Press 2013. All rights reserved.


Structures & Pointers
 At times it is useful to assign pointers to structures.

◦ A pointer to a structure is not itself a structure, but merely a


variable that holds the address of a structure.
◦ This pointer variable takes four bytes of memory just like any
other pointer in a 32-bit machine.
◦ Declaring pointers to structures is basically the same as
declaring a normal pointer.
◦ There are many reasons for using a pointer to a struct. One of them is
to make a two-way communication possible within functions.
◦ This aspect is explained with examples in the following section.
◦ A pointer to a structure is not itself a structure, but merely a variable
that holds the address of a structure.

© Oxford University Press 2013. All rights reserved.


Structures & Pointers
A typical construct for declaring a pointer to a structure will appear as
follows:

struct struct <structure_tag_name>


<structure_tag_name > {
/* structure declaration */ <data_type
{ member_name_1>;
<data_type
<data_type
member_name_2>;
member_name_1>;

<data_type
<data_type
member_name_2>; member_name_n>;
... };
<data_type struct <structure_tag_name>
member_name_n>; *ptr;
}*ptr;
© Oxford University Press 2013. All rights reserved.
Structures & Functions
 Passing and working with pointers to large structures may
be more efficient while passing structures to a function and
working within it.

◦ When a structure is passed as an argument, each member of


the structure is copied.
◦ In fact, each member is passed by value. In case the member
is an array, a copy of this array is also passed.
◦ This can prove to be inefficient where structures are large or
functions are called frequently.
◦ The general construct for passing a structure to a function and
returning a structure is
struct structure_tag function_name(struct
structure_tag structure_variable);

© Oxford University Press 2013. All rights reserved.


Union
A union is a special data type available in C that
allows to store different data types in the same
memory location.
 You 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.
Union
A union is a structure all of whose members share
the same storage.
◦ The amount of storage allocated to a
union is sufficient to hold its largest
member.
◦ At any given time, only one member of the
union may actually reside in that storage.
◦ A union is identified in C through the use of the
keyword union in place of the keyword struct.
◦ Virtually all other methods for declaring and
accessing unions are identical to those for
structures.

© Oxford University Press 2013. All rights reserved.


Union
Declaring a Union and its Members :
The general construct for declaring a
union is given as follows.
union tag_name
{
member1;
...
memberN;
}variable1,variable2,variable3,
…,variableX;
Union
 The general construct of declaring the individual union
variables is
◦ union tag_name variable1,variable2,…,variableX;
 As an example, consider the following declarations for a
union that has a tag named mixed.
union mixed
{
char letter;
fl oat radian;
int number;
};
union mixed all;
◦ The first declaration consists of a union of type mixed, which
consists of a char, float, or int variable as a member.

© Oxford University Press 2013. All rights reserved.


#include <stdio.h>
#include <string.h>

union Data
{ Memory size occupied by data : 20
int i;
float f;
char str[20];
};

int main( )
{

union Data data;

printf("Memory size occupied by data:%d\n", sizeof(data));

return 0;
}
Union
 The union data type was created to prevent the computer
from breaking its memory up into several inefficiently sized
pieces, which is called memory fragmentation.

 Accessing and Initializing the Members of a Union :


◦ Consider, the general declaration construct of a union.
union tag_name
{
member1;
member2;
.. .
memberN;
}variable1,variable2,variable3,…,variableX;

© Oxford University Press 2013. All rights reserved.


Accessing & Initializing the
Members of a Union
◦ For accessing members of, say, variable1 to N of the
union tag_name, the following constructs are used.
variable1.member1
variable2.member2
.. .
variableX.memberN
◦ Only a member that exists at the particular
instance in storage should be accessed.
◦ The general construct for individual initialization of a
union member is
variableX.memberN = constant;
◦ where X is any value 1 to X and N is any value 1 to N.

© Oxford University Press 2013. All rights reserved.


#include <stdio.h>
#include <string.h> data.i : 1917853763
data.f :41223605794860452759994
union Data { 368.000000
int i; data.str : C Programming
float f;
char str[20];
};
values of i and f members of union
int main( ) { got corrupted because the final
value assigned to the variable has
union Data data; occupied the memory location

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

return 0;
}
#include <stdio.h>
#include <string.h>
data.i : 10
union Data { data.f : 220.500000
int i; data.str : C Programming
float f;
char str[20];
};
Here, all the members are getting
int main( ) { printed very well because one
member is being used at a time.
union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

return 0;
}
Structure versus Union

© Oxford University Press 2013. All rights reserved.


Do’s & Don’ts for Unions
 It is important to remember which union member is being used.

◦ If the user fills in a member of one type and then tries to use a different
type, the results can be unpredictable.

 The following operations on union variables are valid.

◦ A union variable can be assigned to another union variable.


◦ A union variable can be passed to a function as a parameter.
◦ The address of a union variable can be extracted by using & operator.
◦ A function can accept and return a union or a pointer to a union.
◦ Don’t try to initialize more than the first union member.
◦ Don’t forget that the size of a union is equal to its largest member.
◦ Don’t perform arithmetical or logical operations on union variables.

© Oxford University Press 2013. All rights reserved.


Enumeration Types
 An enumeration is a set of named integer constants.

 The keyword enum is used to declare an enumeration type.


The general construct used to declare an enumeration type
is enum :

enum <enum_name>
{member1, member2,…, memberN
};

Where,
 The enum_name specifies the enumeration type name.
 members are comma-separated list of identifiers
Each of the symbols in the enumeration list stands for an
integer value, one greater than the symbol that precedes it.
By default, the value of the first enumeration symbol is 0. For
example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Enumeration Types
 The enum tag_name specifies the user-defined type.

 The members are integer constants. By default, the first


member, that is, member1, is given the value 0.

 The second member, member2, is given the value 1.

 Members within the braces may be initialized, in which


case, the next member is given a value one more than the
preceding member. So, each member is given the value of
the previous member plus 1

© Oxford University Press 2013. All rights reserved.


#include <stdio.h>

enum week { sunday, monday, tuesday, wednesday, thursday,


friday, saturday };

int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
output
Day 4
Example

© Oxford University Press 2013. All rights reserved.


Why enums are used in C programming?

Enum variable takes only one value out of many possible values.
Example to demonstrate it.

#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20, Size of enum variable = 4
spades = 3 bytes
} card;

int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
Bitfield
 There are two ways to manipulate bits in C.

◦ One of the ways consists of using bitwise operators.


◦ The other way consists of using bit fields in which the definition and the
access method are based on structure.

 The general format for declaring bit field using a structure is given
as follows.

struct bitfield_tag
{
unsigned int member1: bit_width1;
unsigned int member2: bit_width2;
.. .
unsigned int memberN: bit_widthN;
};
© Oxford University Press 2013. All rights reserved.
Bitfield
 With reference to bitfields, it should be noted that
a field in a word has no address.
 In this construct, the declaration of variable
name is optional. The construct for individually
declaring the variables to this structure is given
by
◦ struct bitfield_tag variable_name;

 Eachbitfield, for example, ‘unsigned int


member1: bit_ width1’, is an integer that has a
specified bit width.

© Oxford University Press 2013. All rights reserved.


Example

© Oxford University Press 2013. All rights reserved.

You might also like