C Programming Lecture 23 Enumeration Types Structures.

31
C Programming C Programming Lecture 23 Lecture 23 Enumeration Types Enumeration Types Structures Structures

Transcript of C Programming Lecture 23 Enumeration Types Structures.

Page 1: C Programming Lecture 23 Enumeration Types Structures.

C ProgrammingC Programming

Lecture 23Lecture 23Enumeration Types Enumeration Types

StructuresStructures

Page 2: C Programming Lecture 23 Enumeration Types Structures.

Enumeration TypesEnumeration Types

Enumeration typesEnumeration types are defined are defined and used by the programmer as and used by the programmer as the need arises.the need arises.• They allow the programmer to They allow the programmer to name a name a finite setfinite set together with together with its its elementselements..– The The elementselements of the finite set are of the finite set are called called enumeratorsenumerators..

Page 3: C Programming Lecture 23 Enumeration Types Structures.

Naming a Finite Set Naming a Finite Set and Declaring Enumeratorsand Declaring Enumerators

enumenum dayday { {sun, mon, tue, wed, thu, fri, satsun, mon, tue, wed, thu, fri, sat};};

The keyword The keyword enumenum is used to is used to declaredeclare an an enumeration type.enumeration type.

The The enumeratorsenumerators above are the identifiers above are the identifiers sun, sun, mon,...,satmon,...,sat..

The keyword The keyword enumenum along with the along with the tag nametag name dayday are used as a are used as a type specifiertype specifier to declare to declare variables of type variables of type enum dayenum day..

enum dayenum day d1d1, , d2d2; /* declares variables ; /* declares variables d1d1 & & d2d2 */ */

Page 4: C Programming Lecture 23 Enumeration Types Structures.

Alternative for Declaring Alternative for Declaring VariablesVariables

On the previous slide, the enumeration On the previous slide, the enumeration type type enum dayenum day was first declared, then was first declared, then variables of that type were declared.variables of that type were declared.• We can do both at the same time.We can do both at the same time.

enum day {sun,mon, tue, wed, thu, fri, sat} enum day {sun,mon, tue, wed, thu, fri, sat} d1d1, , d2d2;;

Page 5: C Programming Lecture 23 Enumeration Types Structures.

What are the Enumerators, What are the Enumerators, Really?Really?

enum day {sun, mon, tue, wed, thu, fri, sat} d1;enum day {sun, mon, tue, wed, thu, fri, sat} d1;

The enumerators sun, mon, ..., sat are The enumerators sun, mon, ..., sat are identifiers:identifiers:• They are They are constantsconstants of type of type intint..• By default, the By default, the first onefirst one is given the value is given the value 00, ,

and and each succeeding oneeach succeeding one has the has the next integernext integer..

Page 6: C Programming Lecture 23 Enumeration Types Structures.

Initialization of Initialization of EnumeratorsEnumerators

enum fruit {enum fruit {appleapple = 7, = 7,pearpear, , orangeorange = 3, = 3,lemonlemon} fruit;} fruit;

Since the enumerator Since the enumerator appleapple has been initialized to has been initialized to 77, , pearpear has a value of has a value of 88..

Since Since orangeorange has a value of has a value of 33, , lemonlemon has a value of has a value of 44..

Page 7: C Programming Lecture 23 Enumeration Types Structures.

Using Enumeration Using Enumeration VariablesVariables

The previously declared variables The previously declared variables d1d1 and and d2d2 can can only be assignedonly be assigned values from the set we named values from the set we named dayday..

d1 = fri;d1 = fri;

d2 = sat;d2 = sat;

Page 8: C Programming Lecture 23 Enumeration Types Structures.

Using Enumeration TypesUsing Enumeration Types

Enumerators are treated as programmer-Enumerators are treated as programmer-specified constants and used to aid specified constants and used to aid program clarity.program clarity.• If necessary, the underlying value can be If necessary, the underlying value can be obtained by using a cast.obtained by using a cast.

• The variables and enumerators in a function The variables and enumerators in a function must all have distinct values.must all have distinct values.

Page 9: C Programming Lecture 23 Enumeration Types Structures.

The typedef FacilityThe typedef Facility

C provides the C provides the typedeftypedef facility so that a facility so that a descriptivedescriptive identifier can be used as identifier can be used as the name of a specific the name of a specific typetype..

typedeftypedef int int colorcolor;;

This makes This makes colorcolor a type that is a type that is synonymous with int, and synonymous with int, and colorcolor can now can now be used as a type in declarations.be used as a type in declarations.

colorcolor red, green, blue; red, green, blue;

Page 10: C Programming Lecture 23 Enumeration Types Structures.

Leaving off the Tag NameLeaving off the Tag Name

enum enum tree_typetree_type {fir,pine} {fir,pine} treetree;;

We can leave out the We can leave out the tag nametag name, , but all but all variablesvariables will have to be will have to be declared when the enumeration is declared when the enumeration is declared:declared:

enum {fir,pine} enum {fir,pine} treetree;;

Page 11: C Programming Lecture 23 Enumeration Types Structures.

StyleStyle

Since enumerators can be mnemonic Since enumerators can be mnemonic (descriptive),their use tends to be (descriptive),their use tends to be self-documenting and is considered good self-documenting and is considered good programming style.programming style.

ExamplesExamples• enum bool {false, true};enum bool {false, true};• enum off_on {off, on};enum off_on {off, on};• enum no_yes {no, yes};enum no_yes {no, yes};• enum speed {slow, fast};enum speed {slow, fast};

Page 12: C Programming Lecture 23 Enumeration Types Structures.

The Structure TypeThe Structure Type

The The structure typestructure type allows the allows the programmer to programmer to aggregate components into aggregate components into a single, named variablea single, named variable..• A structure has A structure has componentscomponents that that are are individually namedindividually named..– These components are called These components are called membersmembers..

• The members of a structure can be of various The members of a structure can be of various types.types.– This allows the programmer to create aggregates This allows the programmer to create aggregates of data that are suitable for each specific of data that are suitable for each specific problem.problem.

• Like arrays and pointers, structures are Like arrays and pointers, structures are considered a considered a derived typederived type..

Page 13: C Programming Lecture 23 Enumeration Types Structures.

The Member and Structure The Member and Structure Pointer Operators “Pointer Operators “..” and “” and “--

>>””

Members of structures are Members of structures are accessed using either:accessed using either:• the the member operatormember operator .. or or• the the structure pointer operatorstructure pointer operator ->->

These operators along with These operators along with ()() and and [][] have the highest precedence. have the highest precedence.

Page 14: C Programming Lecture 23 Enumeration Types Structures.

Declaring StructuresDeclaring Structures

Example Using Playing CardsExample Using Playing Cards• Playing cards have what is known as a pip Playing cards have what is known as a pip value and a suit value.value and a suit value.– The three of spades has a pip value, 3 and a The three of spades has a pip value, 3 and a suit value, spades.suit value, spades.

We can declare the structure type:We can declare the structure type: struct card {struct card {

int pips;int pips; char suit;char suit; };};

to capture the information needed to represent to capture the information needed to represent a playing card.a playing card.

Page 15: C Programming Lecture 23 Enumeration Types Structures.

The Derived Type The Derived Type struct struct cardcard

struct cardstruct card { { int int pipspips;; char char suitsuit;;};};

structstruct is ais a keyword. keyword. cardcard is the structureis the structure tag name. tag name. pipspips is ais a member variable member variable that will take values that will take values

from from 11 to to 1313.. suitsuit is ais a member variable member variable that will take values that will take values

from ‘from ‘cc’, ‘’, ‘dd’, ‘’, ‘hh’, and ‘’, and ‘ss’,representing clubs, ’,representing clubs, diamonds, hearts, and spades.diamonds, hearts, and spades.

Page 16: C Programming Lecture 23 Enumeration Types Structures.

Declaring Variables of the Declaring Variables of the Derived Type Derived Type struct cardstruct card

The declarationThe declarationstruct cardstruct card c1, c2;c1, c2;

allocates space for the identifiers allocates space for the identifiers c1c1 and and c2c2, which are of type , which are of type struct cardstruct card..

To access the To access the membersmembers of of c1c1 and and c2c2, we , we use the structure member operator “use the structure member operator “..”:”:

c1c1..pips = 5; pips = 5; /* a construct of the form *//* a construct of the form */

c1c1..suit = ‘d’; suit = ‘d’; /*/* structure_variablestructure_variable..member_namemember_name */*/

c2c2..pips = 12; pips = 12; /* is used as a variable in the *//* is used as a variable in the */

c2c2..suit = ‘s’; suit = ‘s’; /* same way a simple variable or *//* same way a simple variable or */

/* an element of an array is /* an element of an array is used.*/used.*/

Page 17: C Programming Lecture 23 Enumeration Types Structures.

Uniqueness of Member Uniqueness of Member NamesNames

A A member namemember name must be must be unique within a unique within a specified structurespecified structure..

Since the member must Since the member must alwaysalways be be prefaced or accessed through a unique prefaced or accessed through a unique structure variable identifier, there is structure variable identifier, there is no confusion between members of no confusion between members of different structures having the same different structures having the same namename..

Page 18: C Programming Lecture 23 Enumeration Types Structures.

Example of Same Member Example of Same Member NamesNames

in Different Structures in Different Structures

struct fruitstruct fruit {{ char name[15];char name[15]; int calories;int calories;};};

struct vegetablestruct vegetable {{ char name[15];char name[15]; int calories;int calories;}}

struct fruitstruct fruit aa;;struct vegetablestruct vegetable bb;;

We can access We can access a.caloriesa.calories and and b.caloriesb.calories without without ambiguity.ambiguity.

Page 19: C Programming Lecture 23 Enumeration Types Structures.

Declaration of Variables DuringDeclaration of Variables Duringthe Creation of a Structure Typethe Creation of a Structure Type

It is possible to It is possible to create a structure typecreate a structure type and and declare variablesdeclare variables of that type at the of that type at the same timesame time..

struct cardstruct card { { int pips;int pips; char suit;char suit;

} } cc,, deck[52]deck[52]; ; /* /* c c is a is a variablevariable that can */ that can */ /* store a single card. /* store a single card. deckdeck */ */ /* is the name of an /* is the name of an arrayarray */ */ /* that can store a deck of *//* that can store a deck of */ /* cards. *//* cards. */

Page 20: C Programming Lecture 23 Enumeration Types Structures.

Omission of the Tag NameOmission of the Tag Name

structstruct { { /* Since no tag name is *//* Since no tag name is */ char *last_name;char *last_name; /* used, no variables can *//* used, no variables can */ int student_id; int student_id; /* be declared later in *//* be declared later in */ char grade;char grade; /* the program. *//* the program. */} } s1s1, , s2s2, , s3s3;;

struct studentstruct student { { /* Variables can now be *//* Variables can now be */ char *last_name;char *last_name; /* be declared later in *//* be declared later in */ int student_id;int student_id; /* the program as shown *//* the program as shown */ char grade;char grade; /* below. /* below. UntilUntil the */ the */};}; /* declaration below, /* declaration below, nono */ */

/* /* storage is allocated.storage is allocated. */ */

struct studentstruct student temp, class[100]; temp, class[100];

Page 21: C Programming Lecture 23 Enumeration Types Structures.

Example: Example: class_info.cclass_info.c

See the class_info files in the See the class_info files in the public subdirectory class23.public subdirectory class23.• Note:Note: The structure member The structure member last_namelast_name is declared as is declared as last_name[20];last_name[20]; instead instead of of *last_name *last_name so that the name can be so that the name can be read in from a file rather than being read in from a file rather than being a constant in the program;a constant in the program;

• The 20 can be any number that is The 20 can be any number that is large enough to hold the characters large enough to hold the characters of a name and the null character \0.of a name and the null character \0.

Page 22: C Programming Lecture 23 Enumeration Types Structures.

The Structure Pointer The Structure Pointer Operator Operator ->->

C provides the C provides the structure pointer structure pointer operatoroperator ->-> to access members of a to access members of a structure structure via a pointervia a pointer..• -> is typed on the keyboard as a minus sign -> is typed on the keyboard as a minus sign followed by a greater than sign.followed by a greater than sign.

If a pointer variable is assigned the If a pointer variable is assigned the address of a structure, then a member address of a structure, then a member of the structure can be accessed by:of the structure can be accessed by:

pointer-to-structurepointer-to-structure ->-> member_namemember_name

An equivalent construct is:An equivalent construct is:

((**pointer_to_structure)pointer_to_structure)..member_namemember_name

Page 23: C Programming Lecture 23 Enumeration Types Structures.

Examples of the Two Accessing ModesExamples of the Two Accessing Modes

Declarations and AssignmentsDeclarations and Assignments

struct student temp, struct student temp, *p*p = &temp; = &temp;temp.grade = ‘A’;temp.grade = ‘A’;temp.last_name = “Bushker”;temp.last_name = “Bushker”;temp.student_id = 590017temp.student_id = 590017;;

Expression Expression Equivalent ExpressionEquivalent Expression Conceptual ValueConceptual Value

temp.gradetemp.grade pp -> grade -> grade A Atemp.last_nametemp.last_name pp -> last_name -> last_name BushkerBushkertemp.student_idtemp.student_id pp -> student_id -> student_id 590017590017((*p*p).student_id).student_id p p -> student_id-> student_id 590017590017

Page 24: C Programming Lecture 23 Enumeration Types Structures.

Operators Operators AssociativityAssociativity

() [] . -> ++ () [] . -> ++ ((postfixpostfix)) -- -- ((postfixpostfix)) left to rightleft to right

++ ++ ((prefixprefix)) -- -- ((prefixprefix) ! ~ sizeof(type)) ! ~ sizeof(type) right to leftright to left+ + ((unaryunary)) - - ((unaryunary)) & & ((addressaddress)) * * ((dereferencedereference))

** // %% left to rightleft to right

++ - - left to rightleft to right

<< << >> >> left to rightleft to right

< <= > >= < <= > >= left to rightleft to right

== != == != left to rightleft to right

&& left to rightleft to right

^̂ left to rightleft to right

|| left to rightleft to right

&&&& left to rightleft to right

|||| left to rightleft to right

?:?: right to leftright to left

= += -= *= /= %= >>= <<= &= ^= |= = += -= *= /= %= >>= <<= &= ^= |= right to leftright to left

, , ((comma operatorcomma operator)) left to rightleft to right

Precedence and AssociativityPrecedence and Associativity

Page 25: C Programming Lecture 23 Enumeration Types Structures.

Structures as Arguments to Structures as Arguments to FunctionsFunctions

Traditional CTraditional C allows a allows a pointer to a pointer to a structure typestructure type to be passed as an to be passed as an argument to a function and returned as argument to a function and returned as a value.a value.

ANSI CANSI C also allows also allows structures structures themselvesthemselves to be passed as arguments to to be passed as arguments to functions and returned as values (as a functions and returned as values (as a complete structure).complete structure).• HoweverHowever, a pointer to a structure is still , a pointer to a structure is still the preferred type of function argument and the preferred type of function argument and return value in most cases.return value in most cases.

Page 26: C Programming Lecture 23 Enumeration Types Structures.

Example of Passing Example of Passing a Pointer to a Structure a Pointer to a Structure

TypeType

struct card {struct card { int pips;int pips; char suit;char suit;};};. . .. . .struct card c;struct card c;int pip = 12; int pip = 12; /* the Queen of Hearts *//* the Queen of Hearts */char suit = ‘h’;char suit = ‘h’;. . .. . .assign_valuesassign_values((&c&c, pip, suit); /* Function Call */, pip, suit); /* Function Call */. . .. . .void void assign_valuesassign_values(struct card (struct card *c_ptr*c_ptr, int p, char , int p, char s);s);{{ c_ptrc_ptr->pips = p;->pips = p; c_ptrc_ptr->suit = s;->suit = s;}}

Page 27: C Programming Lecture 23 Enumeration Types Structures.

Assignment of Assignment of StructuresStructures

ANSI C also allows assignment of ANSI C also allows assignment of structures.structures.• If If aa and and bb are variables of the are variables of the same same structure typestructure type, the assignment , the assignment expression expression a = ba = b is allowed. is allowed.

• See the assignment to an array of See the assignment to an array of struct student types in the public struct student types in the public subdirectory file class23 for an subdirectory file class23 for an example of assignment of structures.example of assignment of structures.

• Look in Look in class23class23 and study the and study the programs there.programs there.

Page 28: C Programming Lecture 23 Enumeration Types Structures.

Data StructuresData Structures

In C, structures, pointers, and arrays In C, structures, pointers, and arrays may be combined to create complicated may be combined to create complicated data structuresdata structures..• We have entire courses on this.We have entire courses on this.

Problem solving is enhanced by Problem solving is enhanced by matchingmatching a data structure to the information a data structure to the information that is to be manipulated.that is to be manipulated.• In C, In C, structstruct is an encapsulation is an encapsulation mechanism for a set of mechanism for a set of characteristics that describe a real-characteristics that describe a real-world object such as a student.world object such as a student.

Page 29: C Programming Lecture 23 Enumeration Types Structures.

Initialization of StructuresInitialization of Structures

All All externalexternal and and staticstatic variables, variables, including structure variables, that are including structure variables, that are not explicitly initialized are not explicitly initialized are initialized by the system.initialized by the system.

We can also initialize automatic We can also initialize automatic structures.structures.• Similar to initializing an automatic Similar to initializing an automatic array.array.

Page 30: C Programming Lecture 23 Enumeration Types Structures.

Example of InitializingExample of Initializing Automatic Structure Automatic Structure

VariablesVariables

struct card {struct card {int pips;int pips;char suit;char suit;

};};struct fruit {struct fruit {

char name[15];char name[15];int calories;int calories;

};};. . .. . .

struct cardstruct card c = {12, ‘s’}c = {12, ‘s’};;struct fruitstruct fruit frt = {“plum”, 150}frt = {“plum”, 150};;

Page 31: C Programming Lecture 23 Enumeration Types Structures.

The Use of The Use of typedeftypedef

The typedef facility is often The typedef facility is often used to rename a structure used to rename a structure type.type.• We will see examples of this We will see examples of this when we look at linked lists.when we look at linked lists.