You are on page 1of 71

Enumerated, Structure,

and Union Types


Objectives
❏ To introduce the structure, union, and enumerated types
❏ To use the type definition statement in programs
❏ To use enumerated types, including anonymous types.
❏ To create and use structures in programs
❏ To be able to use unions in programs
❏ To understand the software engineering concept of coupling and
to be able to evaluate coupling between functions.

K.Jayasree PPS 1
Derived Types

K.Jayasree PPS 2
The Type Definition (typedef)

Before discussing the derived types, let’s discuss a C


declaration that applies to all of them—the type
definition. A type definition, typedef, gives a name to a
data type by creating a new type that can then be used
anywhere a type is permitted.

K.Jayasree PPS 3
Ex: typedef int INTERGER;

Type-definition Format

K.Jayasree PPS 4
Enumerated Types
The enumerated type is a user-defined type based on the
standard integer type. In an enumerated type, each
integer value is given an identifier called an enumeration
constant.

Topics discussed in this section:


Declaring an Enumerated Type
Operations on Enumerated Types
Enumeration Type Conversion
Initializing Enumerated Constants
Anonymous Enumeration: Constants
Input/Output Operations
K.Jayasree PPS 5
Declaring an Enumerated Type

Syntax:
enum typeName {identifier list};

Ex: enum color{RED, BLUE, GREEN, WHITE};


The following example defines 3 variables for color type:
enum color productColor;
enum color skyColor;
enum color flagColor;

K.Jayasree PPS 6
Operations on Enumerated Types
Assigning values to enumerated types:
enum color productColor;
enum color skyColor;
enum color flagColor;
productColor=RED;
skyColor=GREEN;
flagColor=YELLOW; //ERROR

productColor=skyColor;
flagColor=skyColor;

K.Jayasree PPS 7
Comparing Enumerated Types:
If(color1 == color2)
……
If(color1 == BLUE)
….
Another use of enumerated types is with the switch statement.
They may be used in case expression.
Ex: enum months{JAN, FEB, MAR,APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
enum months dateMonth;
Switch(dateMonth)
{
case JAN: …
break; Note: we can add, subtract, multiply and divide enumerated
case FEB: … types.
break; we can also pass them to standard and application
K.Jayasree …} functions. PPS 8
Enumeration Type Conversion

Enumerated type conversion:


Enumerated type can be implicitly and explicitly cast.
Ex: Implicit cast
Int x;
Enum color y;
X=BLUE; // valid.x contains1
Y=2: // compiler warning
Ex: explicit cast
Enum color y;
Y=(enum color)2; // valid. Y contains blue

K.Jayasree PPS 9
Initializing Enumerated Constants

Initializing enumerated constants:


enum months{JAN, FEB, MAR,APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
enum months dateMonth;

enum months{JAN=1, FEB, MAR,APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

C also allows us to assign duplicate values to identifiers.


Enum color(RED, ROSE=0, CRIMSON=0, SCARLET =0, BLUE, AUAQ=1,NAVY=1,
GREEN, JADE=2, WHITE};

K.Jayasree PPS 10
Anonymous Enumeration: Constants

If we create an enumerated type without a name,it is an anonymous


enumerated type.

Ex:
enum {space=‘ ‘, comma =‘,’ , colon = ‘:’ ,…….};
enum {OFF, ON};

K.Jayasree PPS 11
PROGRAM 12-1 Print Cable TV Stations

K.Jayasree PPS 12
PROGRAM 12-1 Print Cable TV Stations

K.Jayasree PPS 13
Input/Output Operations

enum months {JAN=1, FEB, MAR,APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
enum months month1;
enum months month2;
Scanf(“%d %d”,&month1,&month2); //Input 1 12
Printf(“%d %d”, month1,month2); // prints 1 12

K.Jayasree PPS 14
Note
Don’t be confused about strings and enumerated types.
“Jan” is a string made of three characters; JAN
as defined in the previous code example, is an
enumerated type (identifier) which
has the integer value 1.

K.Jayasree PPS 15
Structure

 A structure is a collection of related elements, possibly of

different types, having a single name.


 Each element in a structure is called a field.

Topics discussed in this section:


Structure Type Declaration
Initialization
Accessing Structures
Operations on Structures
Complex Structures
Structures and Functions
K.Jayasree PPS 16
Structure Examples

K.Jayasree PPS 17
Note
Elements in a structure can be of the same or different
types. However, all elements in the structure
should be logically related.

K.Jayasree PPS 18
Structure Type Declaration

Tagged Structure

Tagged Structure Format

K.Jayasree PPS 19
Type-defined Structure

Structure Declaration with typedef

K.Jayasree PPS 20
Structure Declaration Format and Example

K.Jayasree PPS 21
Initialization

Initializing Structures

K.Jayasree PPS 22
Accessing Structures

Referencing individual fields:


aStudent.id
aStudent.name
aStudent.gradepoints

Example:
If(sam2.u == ‘A’)
Sam2.x+= sam2.y;

K.Jayasree PPS 23
Structure Direct Selection Operator

K.Jayasree PPS 24
K.Jayasree PPS 25
Multiply Fractions

K.Jayasree PPS 26
Multiply Fractions

K.Jayasree PPS 27
Operations on Structures

Copying a Structure

K.Jayasree PPS 28
Pointers to Structures

Pointers to Structures

K.Jayasree PPS 29
Interpretation of Invalid Pointer Use

K.Jayasree PPS 30
Indirect selection operator ->

Note
(*pointerName).fieldName  pointerName->fieldName.

K.Jayasree PPS 31
Indirect Selection Operator

K.Jayasree PPS 32
Complex Structures
Nested Structure: structures within the structures. We can have structures
as members of a structure.

Nested Structure

K.Jayasree PPS 33
Declaring Nested Structures

K.Jayasree PPS 34
K.Jayasree PPS 35
Referencing nested structures

K.Jayasree PPS 36
Nested structure initialization

STAMP stamp ={ {05, 10, 1986}, {23, 45, 00} };

Structures containing Arrays

Defining Arrays for structures

K.Jayasree PPS 37
Arrays in Structures

K.Jayasree PPS 38
Array initialization in structures

K.Jayasree PPS 39
Structure containing pointers

K.Jayasree PPS 40
Pointers in Structures

K.Jayasree PPS 41
Array of Structures

stuAry[i]; *pStu;

Array of Structures

K.Jayasree PPS 42
K.Jayasree PPS 43
K.Jayasree PPS 44
Insertion sort

Insertion sort is a simple sorting algorithm that works similar to the way you
sort playing cards in your hands. The array is virtually split into a sorted and an
unsorted part. Values from the unsorted part are picked and placed at the
correct position in the sorted part.
Algorithm 
To sort an array of size n in ascending order: 
1: Iterate from arr[1] to arr[n] over the array. 
2: Compare the current element (key) to its predecessor. 
3: If the key element is smaller than its predecessor, compare it to the elements
before. Move the greater elements one position up to make space for the
swapped element.

K.Jayasree PPS 45
 
K.Jayasree PPS 46
Structures And Functions
Sending Individual Members

typedef struct{
int numerator;
int denominator;
}FRACTION;
main()
{
FRACTION fr1,fr2,res;

Passing Structure Members to Functions

K.Jayasree PPS 47
K.Jayasree PPS 48
Sending The Whole Structure

multFr(fr1,fr2);

return res;
Passing and returning structures

K.Jayasree PPS 49
Passing Structures Through Pointers

Passing Structures Through Pointers

K.Jayasree PPS 50
Self Referential Structures

 Self Referential structures are those structures that have one or more


pointers which point to the same type of structure, as their member.
 In other words, structures pointing to the same type of structures are self-
referential in nature.

K.Jayasree PPS 51
Example:
struct node {
    int data1;
    char data2;
    struct node* link;
};
  
int main()
{
    struct node ob;
    return 0;
}

In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the
structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly
before accessing, as by default it contains garbage value.
K.Jayasree PPS 52
Types of Self Referential Structures
1.Self Referential Structure with Single Link.
2.Self Referential Structure with Multiple Links.
Self Referential Structure with Single Link: These structures can have only one
self-pointer as their member. The following example will show us how to connect
the objects of a self-referential structure with the single link and access the
corresponding data members. The connection formed is shown in the following
figure.

                                                                                                                                                  
                                                                                                                   

K.Jayasree PPS 53
#include <stdio.h>
struct node
{
    int data1;
    char data2;
    struct node* link;
};
int main()
{
    struct node ob1; // Node1
    // Initialization
    ob1.link = NULL;    printf("%d", ob1.link->data1);
    ob1.data1 = 10;     printf("\n%d", ob1.link->data2);
    ob1.data2 = 20;     return 0;
    struct node ob2; // Node2 }
    // Initialization
    ob2.link = NULL; Output:30 40
    ob2.data1 = 30;
    ob2.data2 = 40;
    // Linking ob1 and ob2
    ob1.link = &ob2;
K.Jayasree PPS 54
Self Referential Structure with Multiple Links: Self referential structures with
multiple links can have more than one self-pointers. Many complicated data
structures can be easily constructed using these structures. Such structures
can easily connect to more than one nodes at a time. The following example
shows one such structure with more than one links.
The connections made in the above example can be understood using the
following figure.

                                                                                                                                           
                                                                                                                                           
                                    

K.Jayasree PPS 55
#include<stdio.h>
struct node
{
    int data;
    struct node* prev_link;
    struct node* next_link;
};
int main()
{
    struct node ob1; // Node1
    // Initialization
    ob1.prev_link = NULL;
    ob1.next_link = NULL;
    ob1.data = 10;
    struct node ob2; // Node2
    // Initialization
    ob2.prev_link = NULL;
    ob2.next_link = NULL;
    ob2.data = 20;
    struct node ob3; // Node3

K.Jayasree PPS 56
// Initialization
    ob3.prev_link = NULL;
    ob3.next_link = NULL;
    ob3.data = 30;
    // Forward links
    ob1.next_link = &ob2;
    ob2.next_link = &ob3;
    // Backward links
    ob2.prev_link = &ob1;
    ob3.prev_link = &ob2;
    // Accessing  data of ob1, ob2 and ob3 by ob1
    printf("%d\t", ob1.data);
    printf("%d\t", ob1.next_link->data);
    printf("%d\n", ob1.next_link->next_link->data);
    // Accessing data of ob1, ob2 and ob3 by ob2
    printf("%d\t", ob2.prev_link->data);
    printf("%d\t", ob2.data);
    printf("%d\n", ob2.next_link->data);
    // Accessing data of ob1, ob2 and ob3 by ob3 Output:
    printf("%d\t", ob3.prev_link->prev_link->data); 10 20 30
    printf("%d\t", ob3.prev_link->data); 10 20 30
    printf("%d", ob3.data); 10 20 30
    return 0;
K.Jayasree } PPS 57
Applications:
Self referential structures are very useful in creation of other complex
data structures like:
•Linked Lists
•Stacks
•Queues
•Trees
•Graphs etc

K.Jayasree PPS 58
Unions

The union is a construct that allows memory to be


shared by different types of data. This redefinition can
be as simple as redeclaring an integer as four
characters or as complex as redeclaring an entire
structure.

Topics discussed in this section:


Referencing Unions
Initializers
Unions and Structures
Internet Addresses

K.Jayasree pps 59
Unions
K.Jayasree pps 60
Referencing Unions
shareData.num;
shareData.chAry[0];

Initializers

K.Jayasree pps 61
PROGRAM 12-7 Demonstrate Effect of Union

K.Jayasree pps 62
PROGRAM 12-7 Demonstrate Effect of Union

K.Jayasree pps 63
Unions and Structures

A Name Union

K.Jayasree pps 64
PROGRAM 12-8 Demonstrate Unions in Structures

K.Jayasree pps 65
PROGRAM 12-8 Demonstrate Unions in Structures

K.Jayasree pps 66
PROGRAM 12-8 Demonstrate Unions in Structures

K.Jayasree pps 67
Internet Addresses

Ex:
www.open.edu

153.18.8.105

K.Jayasree pps 68
Bit Fields
In C, we can specify size (in bits) of structure and union members. The idea is to
use memory efficiently when we know that the value of a field or group of fields
will never exceed a limit or is within a small range.

K.Jayasree pps 69
Bit Field
The variables defined with a predefined width are called bit fields. A bit field can hold
more than a single bit; for example, if you need a variable to store a value from 0 to 7,
then you can define a bit field with a width of 3 bits as follows −
Bit Field Declaration
The declaration of a bit-field has the following form inside a structure −
struct { type [member_name] : width ; };
The following table describes the variable elements of a bit field −
S.No Element & Description
1 type
An integer type that determines how a bit-field's value is interpreted. The type
may be int, signed int, or unsigned int.
2 member_name
The name of the bit-field.
3 width
The number of bits in the bit-field. The width must be less than or equal to the
bit width of the specified type.

K.Jayasree pps 70
#include <stdio.h>
#include <string.h>
struct
{
unsigned int age : 3;
} Age;
int main( )
{
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
When the above code is compiled it will compile with a warning and
when executed, it produces the following result −
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
K.JayasreeAge.age : 0 pps 71

You might also like