Enum, Struct, & Union typedef - 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. The primary advantage of the type definition is that it allows you to replace a complex name, such as a pointer declaration with a mnemonic that makes a program easier to read and follow. The format for the type definition is as follows: typedeftypeIDENTIFIER ; keyword Any standard or derived type Traditionally uppercase Example: typedefint INTEGER ; you can use the type definition with any type. The above redefines int to INTEGER ( not recommended ) and then declare integer types using the new name. INTEGER count ; Example: typedefchar *STRING ; STRING stringPtrAry[ 20 ] ; the above declares an array of pointers to strings using the new name STRING.
Enum, Struct, & Union Enumerated types - enumerated type, enum, is built on the integer type. In an enumerated type, each integer value is given an identifier called an enumeration constant. This allows us to use symbolic names rather than numbers, which makes our programs much more readable. Once we have defined the enumerated types, we can create variables from them just as we can create variables from the standard types. Syntax: enum tag{ enumeration constants } ; enum tagvariable_identifier ; The tag is an enum identifier This declares an enumerated type of type tag This defines a new enumerated type Example: enum months { jan, feb, march, apr, may, jun, jul, aug, sep, oct, nov, dec } ; The above defines an enumerated type for months. The enumerated constants jan through dec are assigned the values 0 through 11. (jan equates to 0, feb equates to 1 mar to 2 and so on). enummonths hire_month; The above declares a months type variable named hire_month.
Enum, Struct, & Union An alternative way would be to assign integer values to the enumerated constants. Example: enum months { jan = 1, feb = 2, march = 3, apr = 4, may = 5, jun = 6,jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12 } ; OR enum months { jan = 1, feb, march, apr, may, jun, jul, aug, sep, oct, nov, dec } ; In the second example above jan now equal 1 and each successive month is assigned the next integer value in order. Type definition is often used to define enumerated types. Example: typedef enum { jan = 1, feb, march, apr, may, jun, jul, aug, sep, oct, nov, dec } MONTHS; Now a months type can be created with a single type identifier: MONTHS hire_month ;
#include typedef enum {entertainment, rent, utilities, food, clothing, automobile, insurance, miscellaneous} EXPENSE_T; void print_expense(EXPENSE_T expense_kind); int main(void) { EXPENSE_T expense_kind; scanf("%d", &expense_kind); printf("Expense code represents "); print_expense(expense_kind); printf(".\n"); return (0); } Enum, Struct, & Union Place type definitions in global area so they can be used throughout program Example:
print_expense(EXPENSE_T expense_kind) { switch (expense_kind) { case entertainment: printf("entertainment"); break; case rent: printf("rent"); break; case utilities: printf("utilities"); break; case food: printf("food"); break; case clothing: printf("clothing"); break;
#include enum Boolean_enum { FALSE, TRUE }; /* end enum Boolean_enum */ /* Function prototypes: */ void get_month_value(int *month); int main(void) { int month; get_month_value(&month); printf("The month is %d", month); return 0; } // end function main void get_month_value(int *month) { enum Boolean_enum correct_data = FALSE; do { printf("Enter a month as an integer: "); scanf("%d", month); if (*month 12) printf("Incorrect month. Please try again.\n"); else correct_data = TRUE; /* end if */ } while (correct_data == FALSE); /* end do-while */ } /* end function get_month_value */
Enum, Struct, & Union Structure - a structure is a collection of related elements, possibly of different types, having a single name. Each element of a structure is called a field. A field is the smallest element of named data that has meaning. It has the characteristics of the variables we have used in programs. A field differs from a variable primarily in that it is part of a structure. Another way to look at a structure is as a template. A template is a pattern or outline that can be applied to data to extract individual parts. It allows us to refer to a collection of data using a single name and, at the same time, to refer to the individual components through their names. By collecting all the attributes of an object in one structure, we simplify our programs and make them more readable. Structure declaration - the following is the syntax for declaring a structure: struct tag { field-list } variable_identifier ; by giving the structure a tag we can use it to declare variables, parameters, and return types. You can define variables at the same time you define the structure by listing the variables, separated by commas, after the closing brace or you can declare them separately by using the keyword struct followed by the tag followed by the identifier. struct tag identifier ;
Enum, Struct, & Union Example of a structure: typedef struct { charid[ 10 ] ; charname[ 26 ] ; intgradPoints; } STUDENT; STUDENT aStudent;... void printStudent ( STUDENT Stu ) ;... STUDENT getStudent ( void ); You can also initialize a structure at the time of declaration. The rules for structure initialization are similar to the rules for array initialization. The initializers are enclosed in braces and separated by commas. They must match their corresponding types in the structure definition. STUDENT aStudent = {“ ”, “John Doe”, 3}; The most powerful way to define a structure is to use a type definition (typedef). typedef struct {field-list } TYPE-ID ;
Enum, Struct, & Union Accessing Structures - each field in a structure can be accessed and manipulated using expressions and operators. Anything you can do with an individual variable can be done with a structure field. C uses an operator that is common to many other languages, the member operator( or direct component selection operator), which is simply a period (.). Using the student structured declared above, you would refer to the individual components as follows: aStudent. id aStudent. name aStudent. gradePoints id name gradePoints John Doe 3 Structure variable Components Value aStudent
#include typedef struct { int numer ; int denom; } FRACTION ; void main(void) { FRACTION fr1, fr2, res ; printf("Write the first fraction in the form of x/y: \n"); scanf("%d /%d", &fr1.numer, & fr1.denom); printf("Write the second fraction in the form of x/y: \n"); scanf("%d /%d", &fr2.numer, & fr2.denom); res.numer = fr1.numer * fr2.numer; res.denom = fr1.denom * fr2.denom; printf( "\n The result of %d/%d * %d/%d is %d/%d", fr1.numer, fr1.denom, fr2.numer, fr2.denom, res.numer, res.denom ); return; } Structure definition Declaring 3 variables of type FRACTION Enum, Struct, & Union
Structure Operations - The structure is an entity that can be treated as a whole. However, only one operation, assignment, is allowed on the structure itself. That is, a structure can only be copied to another structure of the same type using the assignment operator. STUDENT anotherStudent ; STUDENT aStudent = {“ ”, “John Doe”, 3}; anotherStudent = aStudent; printf(“ %s”,anotherStudent.name ); /*prints John Doe */ Pointers to structures - structures like other types, can be accessed through pointers. STUDENT *ptrStudent ; ptrStudent = &aStudent ; the reference to each of the sample members is as follows: (*ptrStudent).id ; (*ptrStudent).name ; (*ptrStudent).gradePoints ; The parentheses are needed because the precedence of the member operator is higher than the indirection operator. If you forget to put the parentheses, C applies the dot operator first and the asterisk operator next.
Enum, Struct, & Union Another way to deference pointers to structures is to use the selection operator ( or indirect component selection operator ) which is represented by the character sequence - > (minus sign followed by the greater-than sign). ptrStudent - > id; is equivalent to (*ptrStudent).id ; the first format is preferred. Nested Structures - we can have structures as members of a structure. When a structure includes another structure, it is a nested structure. For example, we can have a structure called stamp that stores the date and the time. typedef struct { int month; int day; int year; } DATE ; typedef struct { int hour; int min; int sec; } TIME ; typedef struct { DATE date; TIME time; }STAMP ; STAMP stamp:
Enum, Struct, & Union Nested Structures (continued ) - When you access a nested structure, you must include each level from the highest to the component being referenced. To reference the month in the stamp structure you would write the following: stamp.date.month and to reference the second in the stamp structure: stamp.time.sec Structures containing arrays -Referencing arrays in structures - to reference, first we refer to the structure, then to the array component. When we refer to the array, we can use either index or pointer notation. char fristChar; char *ptrStrName; ptrStrName = aStudent.name; firstChar = *ptrStrName ; firstChar = aStudent.name[0]; Structures and Functions - A function can access the members o a structure in three ways: 1) Individual members can be passed to the function. 2) The whole structure can be passed and the function can access the members. 3) The address of a structure or member can be passed and the function can access the members through indirection and selection operators. Both are equivalent
Enum, Struct, & Union Structures and Functions (continued) - when we pass a structure to a function, C will copy the values to the local structure just as it does for variables. void print_stu_name(STUDENT stu1) { printf(“the students name is %s\n”, stu1.name); return; }