0% found this document useful (0 votes)
60 views32 pages

Unit Vi

The document discusses structures in C programming. It defines a structure as a collection of logically related elements that can be of different types and have a single name. Structures allow storing complex data in a meaningful way and manipulating multiple variables as a group. The document then describes how to define structures using tags, variables, and typedef. It also covers initializing structure variables and the memory allocation for structures.

Uploaded by

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

Unit Vi

The document discusses structures in C programming. It defines a structure as a collection of logically related elements that can be of different types and have a single name. Structures allow storing complex data in a meaningful way and manipulating multiple variables as a group. The document then describes how to define structures using tags, variables, and typedef. It also covers initializing structure variables and the memory allocation for structures.

Uploaded by

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

UNIT-VI

INTRODUCTION
The basic data types in C are int, float and char. using these data types, we can derive some other
data types, the data types that are derived from the basic data types are called derived data types.
We have already discussed three of the six derived types: arrays, functions and pointers. In this
unit, we discuss the three remaining derived types: structure, union and enumerated. We will also
discuss the use of type definition and Bit field. The derived data types are
shown in Figure 5.0.

Figure 4.0 Derived Types in C

STRUCTURES
We have seen that arrays can be used to represent a group of data items that belong to the same
type. However in real world, we often deal with entities that are collection of dissimilar data
items. Using array variables we cannot store different items under one name. C supports a
derived data type known as structure, which is a method for storing data of different types.

Structure Definition
A structure is a collection of logically related elements, possibly of different types, having a
single name.

Advantages
 Structures help to organize complex data in a more meaningful way.
 Being able to manipulate several variables as a single group makes your programs
easier to manage.
 Business data processing uses the concepts of structures in almost every program.
Example, student database and employee database management.

Good candidates for structures:
Time: year, month, day, hour, minutes, second
Complex number: real part, imaginary part
Point in a 2-dimensional plane: x axis, y axis

DEFINITION OF STRUCTURES
As variables are defined before they use in the program, structures are also defined and declared
before they are used. A structure definition forms a template that may be used to crate structure
objects. The variables that make up the structure are called members of the structure.
A structure can be defined using three different ways,

COMPUTER PROGRAMMING/UNIT-VI 1
 Tagged Structure
 Structure Variables
 Typedef Structure

Tagged Structure

The structure definition associated with the structure name is referred as tagged structure. It does
not create an instance of a structure and Does not allocate any memory.

The general form or syntax of tagged structure definition is as follows,


struct tag_name
{
type1 member1;
type2 member2;
……………
……………
};
Where,
 struct is the keyword which tells the compiler that a structure is being defined.
 Tag_name is the name of the structure.
 member1, member2 … are called members of the structure. The members are declared
within curly braces.
 The closing brace must end with the semicolon.
Example: student details using tagged structure

struct student
{
char name [10];
int roll_number;
float avg_marks;
}; // no memory is allocated for the structure
Note the following points with respect to above structure definition,
 struct is the keyword which tells the compiler structure is being defined.
 student is an identifier representing the structure name (tag_name).
 name, roll_number and avg_marks are members of a structure and are themselves are not
variables. They do not occupy any memory.

Memory is not reserved for the structure definition since no variables are associated with the
structure definition. The members of the structure do not occupy any memory until they are
associated with the structure variables.

The declaration of the structure variable takes of the form,

struct tag_name var1, var2…;

COMPUTER PROGRAMMING/UNIT-VI 2
where, struct is the keyword. Tag_name is the name of the structure. Structure variables are
separated by comma, followed by semicolon.

We can declare structure variables any where in the program.

For the above example the variable declaration as follows,

struct student s1; // memory is allocated for the variable

now a variable of type struct student (derived type) is created, the memory is allocated for the
variable s1.

The following figure shows the memory organization for the above example

s1
------Name-------- ------Roll_ Number-- ------Avg_Marks------
<10 bytes> < 2 bytes > < 4 bytes >

Figure 4.1 Memory map for structure variable

The number of bytes allocated for the structure variable is the sum of sizes of the individual
members. In the above example the size of s1=16 bytes (10+2+4).

Note: Normally, structure definition appears at the beginning of the program file, before any
variables or functions defined.

Structure Variables

Here we are combining both the template declaration and variable declaration in one statement,
is referred as structure variables. The syntax of tagged structure is as follows,

struct tag_name
{
type1 member1;
type2 member2;
……………
} var1, var2…;

Where,
 struct is the keyword which tells the compiler that a structure is being defined.
 tag_name is the name of the structure.
 member1, member2 … are called members of the structure. The members are declared
within curly braces.
 var1, var2… are structure variables that follow curly braces. Here each variable occupies
memory.
 The closing brace must end with the semicolon.

COMPUTER PROGRAMMING/UNIT-VI 3
Example: student details using structure variables

struct student
{
char name [10];
int roll_number;
float avg_marks;
} s1;

Here, name, roll_number and avg_marks are the structure members. s1 is the structure variable,
the compiler allocates memory for the variable s1 as shown in Figure 5.1.

We can omit the tag name from the structure definition, the following is valid.

struct
{
char name [10];
int roll_number;
float avg_marks;
} s1, s2;

Typedefined Structure

 The structure definition associated with keyword typedef is called type-defined structure.
 This is the most powerful way of defining the structure.
 The syntax of typedefined structure is

typedef struct
{
type1 member1;
type2 member2;
……
} TYPE_ID;

where,
 typedef is keyword added to the beginning of the definition.
 struct is the keyword which tells the compiler that a structure is being defined.
 member1, member2…are called fields of the structure.
 The closing brace must end with type definition name which in turn ends with semicolon.

Example: Student details

COMPUTER PROGRAMMING/UNIT-VI 4
//Structure Definition
typedef struct
{
char name [10];
int roll_number;
float avg_marks;
} STUDENT; //no memory is allocated for structure
/* structure declaration */
STUDENT s1, s2; //memory is allocated for the variables.

Note: Using typedef it is not possible to declare a variable. But, we can have user defined data
type. TYPE_ID can be treated as the new data type.

INITIALIZATION OF STRUCTURES
The rules for structure initialization are similar to the rules for array initialization. The initializers
are enclosed in braces and separate by commas. They must match their corresponding types in
the structure definition.

The syntax is shown below,

struct tag_name variable = {value1, value2,… valuen};

Structure initialization can be done in any of the following initialization.

Initialization along with Structure definition


Consider the structure definition for student with three fields name, roll number and average
marks. The initialization of variable can be done as shown below,

struct student
{
char name [5];
int roll_number;
float avg;
} s1= {“Ravi”, 10, 67.8};

The various members of the structure have the following values.


----------------------Name---------------------- ------Roll_Number------------------
avg-------------------

R a v i \0 1 0 6 7 . 8

Figure 4.2 Initial Value of S1

COMPUTER PROGRAMMING/UNIT-VI 5
Initialization during Structure declaration
Consider the structure definition for student with three fields name, roll number and average
marks. The initialization of variable can be done as shown below,

struct student
{
char name[5];
int roll_number;
float avg;
};
struct student s1= {“Ravi”, 10, 67.8};

The various members of the structure have the values as shown in Figure 5.2.
We can also initialize multiple variables using comma between variables.

Points to Remember

 The members of the structure cannot be initialized in the structure definition.


For example,
struct s
{
char name [10] ="ravi”;
int rno;
} s1;
is invalid.

 The initial values are assigned to members of the structure on one-to-one basis i.e., the
values are assigned to various members in the order specified from the first member.
For example,
s1= {“ravi”, 60, 56.7};

is valid. Here, the string “ravi” will be assigned to the first member. 60 is assigned to the second
member and 56.7 is assigned to the third member.
 During partial initialization, the values are assigned to members in the order specified and
the remaining members are initialized with garbage values.
For example,
s1= {“ravi”};
will assign the string “ravi” to name and the remaining members are initialized to garbage
values.

However the statement,


s1= {40, 67.8};
is invalid, because, without initializing the first member name, we are trying to initialize last two
members.
 During initialization, the number of initializers should not exceed the number of
members. It leads to syntax error.

COMPUTER PROGRAMMING/UNIT-VI 6
For example,

s1= {“ravi”, 45, 78.9, 89};

the compiler issues a syntax error “too many initializers”

ACCESSING STRUCTURES
We know that variables can be accessed and manipulates using expressions and operators. On
the similar lines, the structure members can be accessed and manipulated. The members of a
structure can be accessed by using dot(.) operator.

dot (.) operator

Structures use a dot (.) operator to refer its elements, also known as period operator.

Before dot, there must always be a structure variable. After the dot, there must always be a
structure element.

The syntax to access the structure members as follows,

structure_variable_name. structure_member_name

For example, consider the example as shown below,


struct student
{
char name [5];
int roll_number;
float avg;
};

struct student s1= {“Ravi”, 10, 67.8};


The members can be accessed using the variables as shown below,
s1.name --> refers the string “ravi”
s1.roll_number --> refers the roll_number 10
s1.avg --> refers avg 67.8

Arrays with in structures:


It is also possible to declare an array as a member of structure, like declaring ordinary variables.
For example to store marks of a student in three subjects the we can have the following
definition of a structure.

struct student
{
char name [5];
int roll_number;

COMPUTER PROGRAMMING/UNIT-VI 7
int marks [3];
float avg;
};

Then the initialization of the array marks done as follows,

struct student s1= {“ravi”, 34, {60,70,80}};

The values of the member marks array are referred as follows,

s1.marks [0] --> will refer the 0th element in the marks
s1.marks [1] --> will refer the 1st element in the marks
s1.marks [2] --> will refer the 2ndt element in the marks

The below program illustrates how to define a structure, declare a structure and access the
members of the structure.

COMPUTER PROGRAMMING/UNIT-VI 8
COMPUTER PROGRAMMING/UNIT-VI 9
STRUCTURE OPERATIONS
Any operation that can be performed on ordinary variables can also be performed on structure
members. But, some operations cannot be performed on structure variables. The following
sections deals with operations that carried on structure and structure members.

Copying of structure Variables or members

Copying of two structure variables is achieved using assignment operator. But, one structure
variable can be assigned to another structure variable of the same type.
Example,
struct student
{
char name [10];
float avg;
} a, b;

a=b; //copies b in to a

a.avg = b.avg; // copies b average in to a.avg

We can not copy the variables of different structure type.

COMPUTER PROGRAMMING/UNIT-VI 10
Comparison of two structure variables or members

Two variables of same structure type or dissimilar type is not allowed.

For example, the following operations are invalid, even though s1 and s2 are of the same type,
s1==s2; (or) s1! = s2; invalid: because comparison is not allowed
between structure variables.

However, the members of two structure variables of same type can be compared the same way as
ordinary variables. s1 and s2 are two
structures, and then the following operations are valid.

peration Meaning
O
Operation Meaning

Compares member1 of a with


ops1.member1 == s2.member1 member1 of b and return true if
they are same, false otherwise.

returns if the member1 of a and


s1.member1 != s2.member1 member1 of b are not same and
false otherwise.

Table 4.1 Comparison of Structure Members

Arithmetic Operations on Structures

The members of a structure are same to any ordinary variable and so any operation that can be
performed on a variable can also be performed on structure members. The following operations
are valid.

COMPUTER PROGRAMMING/UNIT-VI 11
O
Expression Meaning

increments the salary before


=++e.salary accessing its value.

increments the salary after


e.salary++ accessing its value.

Access the address if e.salary.


&e.salary
Access the beginning address of
&e the structure.

Table 4.2 Arithmetic Operations on Structure Members

Note: The arithmetic, relational, logical and other various operations can be performed on
individual members of the structures but not on structure variables.

NESTED STRUCTURES
A structure which includes another structure is called nested structure i.e a structure can be used
as a member of another structure.

The syntax for the nesting of the structure as follows,


struct tag_name1
{
type1 member1;
…….
…….
};

struct tag_name2
{
type1 member1;
……
……
struct tag_name1 var;
……
};

The syntax for accessing members of a nested structure as follows,

outer_structure_variable.innerstructurevariable.membername

COMPUTER PROGRAMMING/UNIT-VI 12
Good candidates for nested structures:

Student: dob -> day, month, year


Employee: allowance -> da, ta, hra
Player: tests, one days, T20

Example: Consider the student information name, roll no, DOB and avg. The DOB consists of
day, month, and year. It can be defined as shown below,

struct data
{
int day;
int month;
int year;
};

struct student
{
char name [10];
int roll_number;
struct data dob;
int marks [3];
float avg;
} s1;
Note that the above structure consists of a member identified by dob whose type is struct data.

The members contained in the inner structure namely day, month and year can be referred to as

s1.dob.day
s1.dob.month
s1.dob.year

An inner-most member in a structure can be accessed by chaining all the concerned structure
variables (from outer-most to inner-most).
The memory organization of variable s1 is shown in Figure 5.3.

s1
name Roll number dob marks year
10 bytes 2 bytes date month year 6 bytes 4 bytes
2 bytes 2 bytes 2 bytes
Figure 4.3: Memory organization of nested structure

We can nest two structures by using the following syntax,

COMPUTER PROGRAMMING/UNIT-VI 13
struct tag_name1
{
type1 member1;
…….
…….
struct tag_name2
{
type1 member1;
……
……
} var;
};

Example
struct student
{
char name [10];
int roll_number;
struct data
{
int day;
int month;
int year;
} dob;
int marks [3];
float avg;
};

In the above definition it is mandatory to initialize variable to the inner most structure. The
members are accessed same way as first method.
Below program illustrates nesting of structures.

COMPUTER PROGRAMMING/UNIT-VI 14
ARRAY OF STRUCTURES
As we have an array of integers, we can have an array of structures also. For example, suppose
we want to store the information of class of students, consisting of name, roll_number and
marks, A better approach would be to use an array of structures.
Array of structures can be declared as follows,

struct tag_name arrayofstructure[size];

After having the above declaration a list of variables of type struct tag_name.

Let’s take an example, to store the information of 3 students, we can have the following structure
definition and declaration,
struct student
{
char name[10];
int rno;
float avg;
};

COMPUTER PROGRAMMING/UNIT-VI 15
struct student s[3];
Defines array called s, which contains three elements. Each element is defined to be of type
struct student.
For the student details, array of structures can be initialized as follows,

struct student s[3]={{“ABC”,1,56.7},{“xyz”,2,65.8},{“pqr”,3,82.4}};

The memory organization of the variables is illustrated in the below Figure,

S
S[0] name rno avg
(10bytes) (2bytes) (4bytes)
S[1] name rno avg
(10bytes) (2bytes (4bytes)
S[2] name rno avg
(10bytes) (2bytes (4bytes)

Figure 5.4: Memory organization of array of structures


// program illustrates reading and displaying of student information for a class of students using
array of structures.
#include<stdio.h>
struct student
{
char rollno[10];
char name[20];
char branch[10];
char gender;
struct birthday
{
int day;
char month[10];
int year;
}DOB;
int sub[3];
float avg;
};
int main()
{
int i,n,j,sum=0;
struct student s[10];
printf(" Enter how many students are there in the class:");
scanf("%d",&n);
printf("\t\t\t\t Enter %d student's details",n);
for(i=0;i<n;i++)
{
printf("\n Enter Roll number of %d Student:",i);

COMPUTER PROGRAMMING/UNIT-VI 16
fflush(stdin);
gets(s[i].rollno);
printf(" Enter the name:");
gets(s[i].name);
printf(" Enter Branch:");
gets(s[i].branch);
printf(" Enter Gender:");
scanf("%c",&s[i].gender);
printf(" Entre DOB:");
scanf("%d%s%d",&s[i].DOB.day,s[i].DOB.month,&s[i].DOB.year);
printf(" Enter the marks of student:");
sum=0;
for(j=0;j<3;j++)
{
scanf("%d",&s[i].sub[j]);
sum=sum+s[i].sub[j];
}
s[i].avg=sum/3.0;
}
printf("\n******************************************");
printf("\n\t\t\t Student details:");
printf("\n******************************************");
for(i=0;i<n;i++)
{
printf ("\n Student %d:",i+1);
printf ("\nRoll number:%s\n
Name:%s",s[i].rollno,s[i].name);
printf ("\nDOB:%d-%s-%d”,
s[i].DOB.day,s[i].DOB.month,s[i].DOB.year);
printf ("\nAverage=%f", s[i].avg);
}
return 0;
}

STRUCTURES AND FUNCTIONS


We should note that structures are more useful if we are able to pass them to functions and return
them. The structures members can be passed to the function in various ways as shown below,

1. BY passing individual members of structure


2. By passing the whole structure
3. By passing structures through pointers

Passing Individual Members

COMPUTER PROGRAMMING/UNIT-VI 17
The first method is to pass each member of the structure as an actual argument of the function
call. The actual arguments are treated independently like ordinary variables.
// Passing individual structure elements

COMPUTER PROGRAMMING/UNIT-VI 18
Explanation
Observe that in the declaration of the structure, rno is declared as int, marks are declared as
integer array and avg as float. Therefore, when we call the function display using

display (s1.rno, s1.marks, &s1.avg);

We are passing the structure individual member value, the base address of the array marks and
the address of structure member. Thus, this is a mixed of call-a call by reference as well as a call
by value.
Note: This method is inefficient when the structure size becomes large. A better way would be to
pass the entire structure variable at a time.

Passing Whole Structure


The second method involves passing a copy of the entire structure to the called function. Any
changes to structure members within the function are not reflected in the original structure. It is
therefore, necessary for the function to return the entire structure back to the calling function.

The general format of sending a copy of a structure to the called function is:

return_type function_name (structure_variable_name);

The called function takes the following form:

data_type function_name(struct_type tag_name)


{
………
………
return(expression);
}

The called function must be declared for its type, appropriate to the data type it is expected to
return.
The structure variable used as the actual argument and the corresponding formal argument in the
called function must of the same struct type.

COMPUTER PROGRAMMING/UNIT-VI 19
The return statement is necessary only when the function is returning some data back to the
calling function. The expression may be any simple variable or structure variable or an
expression using simple variables.

When a function returns a structure, it must be assigned to a structure of identical type in the
calling function. The called functions must be declared in the calling function appropriately.
// Passing Entire Structure

Explanation
Note that here the calling of function fun becomes quite compact, fun (s1); Then the formal
argument in the called function defined as struct type struct student.

Returning Structure from a function


It is also possible that using return statement we can return structure to the calling function. Here
the return type of the function and the return value both must be of type structure.

COMPUTER PROGRAMMING/UNIT-VI 20
When the function call comes with an assignment to the structure variable, after executing the
called function the structure is returned and it is copied into the structure variable in the
assignment statement.
// Program illustrating function returning structure

TYPEDEF
C supports a feature known as “type definition” that allows users to define an identifier that
would represent an existing data type. Its purpose is to redefine the name of an existing variable
type.

The general syntax of the typedef is as follows,


typedef data_type IDENTIFIER;

COMPUTER PROGRAMMING/UNIT-VI 21
where,
 _typedef is the keyword tells the compiler about the type definition.
 data_type refers to an existing data type.
 IDENTIFIER refers the “new” name given to the data type.
 Usually, uppercase letters are used to make it clear that we are dealing with a renamed
data type
Note that using typedef, we are not creating new data types. Instead we are creating only new
name for the existing data type. These new data type names are called user-defined data types.

Suppose we want to store marks scored in various subjects in variables sub1, sub2 and sub3.
These variables can be declared as follows,

int sub1, sub2, sub3;

Using the user-defined data types, the variables can be declared as shown below,

typedef int MARKS;


MARKS sub1, sub2, sub3;

Advantages
 Provides a meaningful way of declaring the variables.
 Increase the readability of the program.
 A complex declaration can be reduced to short and meaningful declaration.
 typedef is widely used while dealing with structures.

COMPUTER PROGRAMMING/UNIT-VI 22
typedef with structures

using typedef, it is efficient way to define a structure. It can be defined as follows,

typedef struct
{
type1 member1;
type2 member2;

} TYPE-ID;

Following are examples of typedef structure

struct employee
{
char name [30];
int age;
float b_sal;
};
typedef Struct employee EMP;
EMP e1, e2;

typedef struct employee


{
char name [30];
int age;
float b_sal;
} EMP;
EMP e1, e2;

members can be accessed same way as normal structure. But here we are creating new type. For
the above example the type name is EMP.

The below program illustrates the definition of structure with typedef, declaring variables and
accessing members.

COMPUTER PROGRAMMING/UNIT-VI 23
STRUCTURES AND POINTERS

COMPUTER PROGRAMMING/UNIT-VI 24
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly we can have a
pointer pointing to a struct. Such pointers are known as ‘structure pointers’.

To access the values of the members of the structure using pointers we need to perform following things,

1. Declare structure variable: struct tag_name var;


2. Declare a pointer to a structure: struct tag_name *ptr;
3. Store the address of structure variable in structure pointer: ptr=&var;
4. Access the members of the structure.

Members of the structures can be accessed in following ways.


Using De-Reference Operator * and Dot (.) Operator

If ptr is a pointer to a structure, then the structure itself can be accessed using indirection operator as
shown below,

struct tag_Name *ptr; // Refers to the whole structure

Once the structure pointer is initialized, then each member of the structure can be accessed using dot
operator as shown below,

(*ptr).structure_member1
(*ptr).structure_member2

Let’s take the following segment of code

struct student
{
int rno;
char name[10];
float avg;
};

struct student s1={101,”ABC”,78.98};


struct student *ptr;
ptr=&s1;

Now the members of the structure can be accessed by using the dot operator as shown below,

(*ptr).name // Access the name


(*ptr).rno // Access roll number
(*ptr).avg // Access average

Note: The parenthesis to all three expressions is necessary. We should not omit the parenthesis. For
example,

*ptr .name // invalid way of accessing the member

Using Selection Operator (->)

COMPUTER PROGRAMMING/UNIT-VI 25
If ptr is a pointer to structure, then the members of the structure can also be accessed using selection
operator denoted by ->(which is formed by minus sign and greater than symbol).
Using this various members of the structure can be accessed as shown below,

ptr -> structrure_member

For the above example the members can be accessed as follows,

ptr - > name // Access the name


ptr - > rno // Access roll number
ptr - > avg // Access average

Remember that on the left hand side of the dot operator, there must always be a structure variable,
whereas on the left hand side of -> operator there must be always be a pointer to structure. This method is
efficient, preferred over the previous method.

s1.rno s1.name s1.avg


101 ABC 78.98

4001 4003 4013

ptr
4001
5001

Figure 5.5: Memory Representation of Structure Pointer

The arrangement of structure variable and pointer to structure in memory is as shown in the Figure 5.5,

// C program to read and display student details using pointer to structure

// C program to read and display student details using pointer to structure

COMPUTER PROGRAMMING/UNIT-VI 26
COMPUTER PROGRAMMING/UNIT-VI 27
SELF-REFERENTIAL STRUCTURE

 A structure definition which includes at least one member as a pointer to the same structure is
known as self-referential structure.
 Can be linked together to form useful data structures such as lists, queues, stacks and trees.
 Terminated with a NULL pointer (0).

The syntax for using the self referential structure as follows,


Struct tag_Name
{
type1 member1;
type2 member2;
….
Struct tag_Name *next;
};

Example,
struct node
{
I int data;
struct node *next;
} n1, n2;

UNIONS

 A union is one of the derived data type.


 Union is a collection of variables referred under a single name.
 The syntax, declaration and use of union is similar to the structure but its functionality is
different.
 The major distinction between structure and union is, in terms of storage.
 In structure each member has its own storage location.
 Whereas all the members of a union use the same location.
 Although a union may contain many members of different types, it can handle only one member
at a time.

The general format or syntax of a union definition is as follows,


union tag_name
{
type1 member1;
type2 member2;
……..
……..
};

COMPUTER PROGRAMMING/UNIT-VI 28
Observe the following points while defining a union.

 union is the keyword which tells the compiler that a union is being defined.
 member1, member2, … are called members(or fields) of the union.
 The members are declared within curly braces.
 The compiler allocates a piece of storage that is large enough to hold the largest variable type in
the union.
 There should be semicolon at the end of closing braces.

A union variable can be declared same way as structure variable.

union tag_name var1, var2...;

COMPUTER PROGRAMMING/UNIT-VI 29
Difference between Structure and Union

Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a
structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size of memory by considering the size of the
structure is greater than or equal to the largest memory. So, size of union is
sum of sizes of its members. The equal to the size of largest member.
smaller members may end with unused
slack bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned unique storage area of location. individual members of union.
4. The address of each member will be 4. The address is same for all the
in ascending order This indicates that members of a union. This indicates that
memory for each member will start at every member begins at the same offset
different offset values. value.
5 Altering the value of a member will 5. Altering the value of any of the
not affect other members of the member will alter other member values.
structure.
6. Individual member can be accessed at 6. Only one member can be accessed at
a time a time.
7. Several members of a structure can 7. Only the first member of a union can
initialize at once. be initialized.

COMPUTER PROGRAMMING/UNIT-VI 30
ENUMERATED TYPES

 We know that words speak more than numbers (as pictures speak more than words).
 For example we may use integers 1, 2, 3,.. 12 to represent months for easy programming.
 It is more readable and understandable if we replace these numbers by some meaningful and
descriptive names such as Jan, Feb… Dec.
 This concept of replacing integers by some descriptive names gives rise to new data type called
enumerated type.
 An enumerated data type is a user defined data type which can take the integer values from a list.
 These integer values are replaced by meaningful and descriptive names so as to enhance the
readability of the program.
 These descriptive names are called enumerators or enumerator constants.

Declaring an Enumerated Type

To declare an enumerated type, we must declare its identifier and its values. Because it is derived from
integer type, its operations are the same as for integers.

Syntax for defining an enumerated type is as follows,


enum type_Name
{
member1;
member2;
….
….
};
Where,

 enum is the keyword tells the compiler about enumerated type definition.
 enum type_Name together represent the user defined data type.
 member1, member2… are integer constants but represented using descriptive names. These are
called enumerator constants or enumerators.
 The definition terminated with a semicolon.

The syntax for declaring the variables are shown below,

enum type_Name var;

Example:

#include<stdio.h>
enum day{MON,TUE,WED,THU,FRI,SAT,SUN};
void main()
{
enum day d;
printf("Enter the choice: ");
scanf("%d",&d);

COMPUTER PROGRAMMING/UNIT-VI 31
switch(d)
{
case MON:printf("Monday");break;
case TUE:printf("Tuesday");break;
case WED:printf("Wednesday");break;
case THU:printf("Thursday");break;
case FRI:printf("Friday");break;
case SAT:printf("Saturday");break;
case SUN:printf("Sunday");break;
default:printf("invalid choice");
}
}
Output:
Enter the choice: 5
Saturday

COMPUTER PROGRAMMING/UNIT-VI 32

You might also like