Structures, Unions, and Enumerations
Structures, Unions, and Enumerations
STRUCTURES, UNIONS,
AND ENUMERATIONS
Declaring Structures
A structure is a collection of one or more components
(members), which may be of different types. (Structures are
called records in many other programming languages;
members are known as fields.)
Declaring structure variables can be done as follows:
struct {
char name[25];
int id, age;
char sex;
} s1, s2;
Declaring Structures
Member names dont conflict with any other names in a
program.
Structure variables may be initialized:
struct {
char name[25];
int id, age;
char sex;
} s1 = { "Smith, John", 2813, 25, 'M'},
s2 = { "Smith, Mary", 4692, 23, 'F'};
Structure Tags
A structure can be given a name (a structure tag) for later
use:
struct student {
char name[25];
int id, age;
char sex;
};
struct student s1, s2;
Structure Tags
As an alternative, we can use typedef to name a
structure:
typedef struct {
char name[25];
int id, age;
char sex;
} Student;
Student s1, s2;
Unions
A union is similar to a structure, except that its members
are overlaid (located at the same memory address).
Example:
union {
int i;
double d;
} u;
Unions
Unions have the same properties as structures:
Unions can be initialized (the initializer specifies the value
of the first member).
Unions can be identified by tags or type names.
Unions can be assigned, passed to functions, and returned
by functions.
Uses of unions:
To save space.
To view a data item in two or more different ways.
To build heterogeneous data structures.
Enumerations
An enumeration is a collection of named integer
constants.
Enumerations are defined in a manner similar to
structures and unions:
enum bool {FALSE, TRUE};
enum rank {TWO, THREE, FOUR, FIVE, SIX, SEVEN,
EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE};
enum suit {CLUBS, DIAMONDS, HEARTS, SPADES};
enum EGA_colors {BLACK, BLUE, GREEN, CYAN, RED,
MAGENTA, BROWN, LT_GRAY, DK_GRAY, LT_BLUE, LT_GREEN,
LT_CYAN, LT_RED, LT_MAGENTA, YELLOW, WHITE};