C Program Design C Structures Unions Bit Manipulations

C Program Design C Structures, Unions, Bit Manipulations and Enumerations 主講人:虞台文

Content l Introduction l Structure Definitions l Initializing Structures l Accessing Members of Structures l Using Structures with Functions typedef l Unions l Bitwise Operators l Bit Fields l Enumeration Constants l

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Introduction

Main Topics l Structure – – l Union – l l Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees Allowed data type being overloaded Bit fields Enumeration

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Structure Definitions
![Structure Definitions struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; Structure Definitions struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth;](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-6.jpg)
Structure Definitions struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; l l A structure definition does not reserve space in memory. Instead, creates a new data type used to define structure variables.
![Define Structure Variables (I) struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Define Structure Variables (I) struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year.](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-7.jpg)
Define Structure Variables (I) struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; struct Personal. Data teacher, students[51], *p;
![Define Structure Variables (II) struct Personal. Data { struct Personal. Data char name[NAMESIZE]; { Define Structure Variables (II) struct Personal. Data { struct Personal. Data char name[NAMESIZE]; {](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-8.jpg)
Define Structure Variables (II) struct Personal. Data { struct Personal. Data char name[NAMESIZE]; { char address[ADDRSIZE]; name[NAMESIZE]; int char Year. Of. Birth; address[ADDRSIZE]; int char Month. Of. Birth; Year. Of. Birth; int Day. Of. Birth; int Month. Of. Birth; }; int Day. Of. Birth; } teacher, students[51], struct Personal. Data teacher, *p; students[51], *p; // variable identifier follows type
![Define Structure Variables (III) struct Personal. Data { struct Personal. Data char name[NAMESIZE]; { Define Structure Variables (III) struct Personal. Data { struct Personal. Data char name[NAMESIZE]; {](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-9.jpg)
Define Structure Variables (III) struct Personal. Data { struct Personal. Data char name[NAMESIZE]; { char address[ADDRSIZE]; typedef struct _tag. Personal. Data name[namesize]; int char Year. Of. Birth; { address[addresssize]; int char Month. Of. Birth; char name[NAMESIZE]; Year. Of. Birth; int Day. Of. Birth; char address[ADDRSIZE]; int Month. Of. Birth; }; int Year. Of. Birth; int Day. Of. Birth; int students[51], Month. Of. Birth; *p; } teacher, struct Personal. Data teacher, students[51], *p; int Day. Of. Birth; // variable identifier follows type } Personal. Data; Personal. Data teacher, students[51], *p;
![Valid Operations l l struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Valid Operations l l struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year.](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-10.jpg)
Valid Operations l l struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; struct Personal. Data x, teacher, students[51], *p; Assigning a structure to a structure of the same type x = teacher; teacher = *p; students[i] = x; Taking the address (&) of a structure p = &students[i]; Accessing the members of a structure gets(students[0]. name); p->Year. Of. Birth = 88; Using the sizeof to determine the size of a structure size = sizeof(struct Personal. Data); size = sizeof(x);

#include <stdio. h> Example #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; main() { struct Personal. Data student; // Enter the student's record printf("Enter name of the student: "); gets(student. name); printf("Enter address: "); gets(student. address); printf("Enter birthday: yy/mm/dd: "); scanf("%2 d/%2 d", &student. Year. Of. Birth, &student. Month. Of. Birth, &student. Day. Of. Birth); printf("nn"); // Print out the student record printf("Student name: %sn", student. name); printf("Address: %sn", student. address); printf("Bithday: %2 d/%2 dn", student. Year. Of. Birth, student. Month. Of. Birth, student. Day. Of. Birth); }

#include <stdio. h> Example #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; main() { struct Personal. Data student; // Enter the student's record printf("Enter name of the student: "); gets(student. name); printf("Enter address: "); gets(student. address); printf("Enter birthday: yy/mm/dd: "); scanf("%2 d/%2 d", &student. Year. Of. Birth, &student. Month. Of. Birth, &student. Day. Of. Birth); printf("nn"); // Print out the student record printf("Student name: %sn", student. name); printf("Address: %sn", student. address); printf("Bithday: %2 d/%2 dn", student. Year. Of. Birth, student. Month. Of. Birth, student. Day. Of. Birth); }

#include <stdio. h> Example #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; main() { struct Personal. Data student; // Enter the student's record printf("Enter name of the student: "); gets(student. name); printf("Enter address: "); gets(student. address); printf("Enter birthday: yy/mm/dd: "); scanf("%2 d/%2 d", &student. Year. Of. Birth, &student. Month. Of. Birth, &student. Day. Of. Birth); get. Person. Info(&student); printf("nn"); // Print out the student record printf("Student name: %sn", student. name); printf("Address: %sn", student. address); printf("Bithday: %2 d/%2 dn", student. Year. Of. Birth, student. Month. Of. Birth, student. Day. Of. Birth); show. Person. Info(&student); }

Example // main. c #include <stdio. h> #include "person. h" main() { struct Personal. Data student; // Enter the student's record get. Person. Info(&student); printf("nn"); // Print out the student record show. Person. Info(&student); } // person. h #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; void get. Person. Info(struct Personal. Data *); void show. Person. Info(struct Personal. Data *);

// person. h #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data // person. c { #include <stdio. h> char name[NAMESIZE]; #include "person. h" char address[ADDRSIZE]; int Year. Of. Birth; Month. Of. Birth; void get. Person. Info(struct int Personal. Data *p) int Day. Of. Birth; { printf("Enter name: }; "); Example // main. c gets(p->name); void get. Person. Info(struct Personal. Data *); #include <stdio. h>printf("Enter address: "); void show. Person. Info(struct Personal. Data *); #include "person. h" gets(p->address); printf("Enter birthday: yy/mm/dd: "); main() scanf("%2 d/%2 d", &p->Year. Of. Birth, { &p->Day. Of. Birth); struct Personal. Data&p->Month. Of. Birth, student; } // Enter the student's record get. Person. Info(&student); void show. Person. Info(struct Personal. Data *p) { printf("nn"); } printf("Name: %sn", p->name); printf("Address: // Print out the student record %sn", p->address); printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, show. Person. Info(&student); p->Month. Of. Birth, p->Day. Of. Birth); }

// person. h #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data // person. c { #include <stdio. h> char name[NAMESIZE]; #include "person. h" char address[ADDRSIZE]; int Year. Of. Birth; Month. Of. Birth; void get. Person. Info(struct int Personal. Data *p) int Day. Of. Birth; { printf("Enter name: }; "); Example // main. c gets(p->name); void get. Person. Info(struct Personal. Data *); #include <stdio. h>printf("Enter address: "); void show. Person. Info(struct Personal. Data *); #include "person. h" gets(p->address); printf("Enter birthday: yy/mm/dd: "); main() scanf("%2 d/%2 d", &p->Year. Of. Birth, { &p->Day. Of. Birth); struct Personal. Data&p->Month. Of. Birth, student; } // Enter the student's record get. Person. Info(&student); void show. Person. Info(struct Personal. Data *p) { printf("nn"); } printf("Name: %sn", p->name); printf("Address: // Print out the student record %sn", p->address); printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, show. Person. Info(&student); p->Month. Of. Birth, p->Day. Of. Birth); }

sizeof Operator struct Some. Data { char a. Char; int an. Int; float a. Float; double a. Double; }; sizeof(struct Some. Data) = ?

#include <stdio. h> #include <limits. h> #include <float. h> struct Some. Data { char a. Char; int an. Int; float a. Float; double a. Double; }; sizeof Operator main() { char mark[]={'M', 'A', 'R', 'K'}; struct Some. Data x; printf("sizeof(struct Some. Data) = %dnn", sizeof(struct Some. Data)); x. a. Char = 'A'; x. an. Int = INT_MAX; x. a. Float = FLT_MAX; x. a. Double = DBL_MAX; printf("Address printf("Address } of of of x: %pn", &x); x. a. Char: %pn", &x. a. Char); x. an. Int: %pn", &x. an. Int); x. a. Float: %pn", &x. a. Float); x. a. Double: %pn", &x. a. Double);

#include <stdio. h> #include <limits. h> #include <float. h> struct Some. Data { char a. Char; int an. Int; float a. Float; double a. Double; }; sizeof Operator main() { char mark[]={'M', 'A', 'R', 'K'}; struct Some. Data x; printf("sizeof(struct Some. Data) = %dnn", sizeof(struct Some. Data)); x. a. Char = 'A'; x. an. Int = INT_MAX; x. a. Float = FLT_MAX; x. a. Double = DBL_MAX; printf("Address printf("Address } of of of x: %pn", &x); x. a. Char: %pn", &x. a. Char); x. an. Int: %pn", &x. an. Int); x. a. Float: %pn", &x. a. Float); x. a. Double: %pn", &x. a. Double);

sizeof Operator struct Some. Data { char a. Char; int an. Int; float a. Float; double a. Double; }; l Because the size of data items of a particular type is machine dependent and because storage alignment considerations are machine dependent, so too is the representation of a structure. sizeof(struct Some. Data) = ?

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Initializing Structures

Example // person. c #include <stdio. h> #include "person. h" // person. h #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; void get. Person. Info(struct Personal. Data *p) { printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2 d/%2 d", &p->Year. Of. Birth, &p->Month. Of. Birth, &p->Day. Of. Birth); } void show. Person. Info(struct Personal. Data *p) { printf("Name: %sn", p->name); printf("Address: %sn", p->address); printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, p->Month. Of. Birth, p->Day. Of. Birth); } void get. Person. Info(struct Personal. Data *); void show. Person. Info(struct Personal. Data *);

Example // person. c #include <stdio. h> #include "person. h" // main. c void get. Person. Info(struct Personal. Data *p) #include <stdio. h> { #include "person. h" // person. h #define NAMESIZE 50 #define ADDRSIZE 80 struct Personal. Data { char name[NAMESIZE]; char address[ADDRSIZE]; int Year. Of. Birth; int Month. Of. Birth; int Day. Of. Birth; }; } printf("Enter name: "); gets(p->name); main()address: "); printf("Enter { gets(p->address); struct Personal. Data student = { printf("Enter birthday: yy/mm/dd: "); scanf("%2 d/%2 d", &p->Year. Of. Birth, "Hale-Evans, Ron", &p->Month. Of. Birth, &p->Day. Of. Birth); "Seattle, Washington", 1965, 6, void show. Person. Info(struct Personal. Data *p) 27 { }; %sn", p->name); printf("Name: printf("Address: %sn", p->address); printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, // Print out the student record p->Month. Of. Birth, p->Day. Of. Birth); } show. Person. Info(&student); } void get. Person. Info(struct Personal. Data *); void show. Person. Info(struct Personal. Data *);

Example // main. c #include <stdio. h> #include "person. h" // person. c #include <stdio. h> #include "person. h" void get. Person. Info(struct Personal. Data *p) { printf("Enter name: "); gets(p->name); main() printf("Enter address: "); { gets(p->address); struct Personal. Data persons[] = { printf("Enter birthday: yy/mm/dd: "); // person. h {"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27}, scanf("%2 d/%2 d", &p->Year. Of. Birth, #define NAMESIZE 50 {"Liddell, Alice", "Wonderland", 1852, 5, 4}, &p->Month. Of. Birth, &p->Day. Of. Birth); #define ADDRSIZE 80 } "The Galaxy", 1961, 15} {"Adams, Douglas", struct Personal. Data }; { void show. Person. Info(struct Personal. Data *p) struct Personal. Data *p; char name[NAMESIZE]; { int address[ADDRSIZE]; i; char printf("Name: %sn", p->name); int Year. Of. Birth; printf("Address: %sn", p->address); int // Month. Of. Birth; Print out the records printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, int Day. Of. Birth; p->Month. Of. Birth, p->Day. Of. Birth); for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct Personal. Data); i++){ }; } Show. Person. Info(p++); printf("n"); Personal. Data *); void get. Person. Info(struct void }show. Person. Info(struct Personal. Data *); }

Example // main. c #include <stdio. h> #include "person. h" // person. c #include <stdio. h> #include "person. h" void get. Person. Info(struct Personal. Data *p) { printf("Enter name: "); gets(p->name); main() printf("Enter address: "); { gets(p->address); struct Personal. Data persons[] = { printf("Enter birthday: yy/mm/dd: "); // person. h {"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27}, scanf("%2 d/%2 d", &p->Year. Of. Birth, #define NAMESIZE 50 {"Liddell, Alice", "Wonderland", 1852, 5, 4}, &p->Month. Of. Birth, &p->Day. Of. Birth); #define ADDRSIZE 80 } "The Galaxy", 1961, 15} {"Adams, Douglas", struct Personal. Data }; { void show. Person. Info(struct Personal. Data *p) struct Personal. Data *p; char name[NAMESIZE]; { int address[ADDRSIZE]; i; char printf("Name: %sn", p->name); int Year. Of. Birth; printf("Address: %sn", p->address); int // Month. Of. Birth; Print out the records printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, int Day. Of. Birth; p->Month. Of. Birth, p->Day. Of. Birth); for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct Personal. Data); i++){ }; } Show. Person. Info(p++); printf("n"); Personal. Data *); void get. Person. Info(struct void }show. Person. Info(struct Personal. Data *); }

Example // main. c #include <stdio. h> #include "person. h" // person. c #include <stdio. h> #include "person. h" void get. Person. Info(struct Personal. Data *p) { printf("Enter name: "); gets(p->name); main() printf("Enter address: "); { gets(p->address); struct Personal. Data persons[] = { printf("Enter birthday: yy/mm/dd: "); // person. h {"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27}, scanf("%2 d/%2 d", &p->Year. Of. Birth, #define NAMESIZE 50 {"Liddell, Alice", "Wonderland", 1852, 5, 4}, &p->Month. Of. Birth, &p->Day. Of. Birth); #define ADDRSIZE 80 } "The Galaxy", 1961, 15} {"Adams, Douglas", struct Personal. Data }; { void show. Person. Info(struct Personal. Data *p) struct Personal. Data *p; char name[NAMESIZE]; { int address[ADDRSIZE]; i; char printf("Name: %sn", p->name); int Year. Of. Birth; printf("Address: %sn", p->address); int // Month. Of. Birth; Print out the records printf("Bithday: %2 d/%2 dn", p->Year. Of. Birth, int Day. Of. Birth; p->Month. Of. Birth, p->Day. Of. Birth); for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct Personal. Data); i++){ }; } Show. Person. Info(p++); printf("n"); Personal. Data *); void get. Person. Info(struct void }show. Person. Info(struct Personal. Data *); }
![Initializing Structures // initialized when defined struct Personal. Data persons[] = { {"Hale-Evans, Ron", Initializing Structures // initialized when defined struct Personal. Data persons[] = { {"Hale-Evans, Ron",](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-27.jpg)
Initializing Structures // initialized when defined struct Personal. Data persons[] = { {"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27}, {"Liddell, Alice", "Wonderland", 1852, 5, 4}, {"Adams, Douglas", "The Galaxy", 1961, 15} }; struct Personal. Data class. Leader, friend; // initialized using assignment operator class. Leader = persons[1]; // Initialized field by field strcpy(friend. name, "George Lin"); strcpy(friend. address, "Taipei Taiwan"); friend. Year. Of. Birth = 1978; friend. Month. Of. Birth = 12; friend. Day. Of. Birth = 24;
![Initializing Structures // initialized when defined struct Personal. Data persons[] = { {"Hale-Evans, Ron", Initializing Structures // initialized when defined struct Personal. Data persons[] = { {"Hale-Evans, Ron",](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-28.jpg)
Initializing Structures // initialized when defined struct Personal. Data persons[] = { {"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27}, {"Liddell, Alice", "Wonderland", 1852, 5, 4}, {"Adams, Douglas", "The Galaxy", 1961, 15} }; struct Personal. Data class. Leader, friend, *p; // initialized using assignment operator class. Leader = persons[1]; // Initialized field by field using a pointer p = &friend; strcpy(p->name, "George Lin"); strcpy(p->address, "Taipei Taiwan"); p->Year. Of. Birth = 1978; p->Month. Of. Birth = 12; p->Day. Of. Birth = 24;

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Accessing Members of Structures

Accessing structure members l Dot operator (. ) for structure variables struct Personal. Data friend; strcpy(friend. name, "George Lin"); strcpy(friend. address, "Taipei Taiwan"); friend. Year. Of. Birth = 1978; friend. Month. Of. Birth = 12; friend. Day. Of. Birth = 24; l Arrow operator (->) for pointers struct Personal. Data friend, *p; p = &friend; strcpy(p->name, "George Lin"); strcpy(p->address, "Taipei Taiwan"); p->Year. Of. Birth = 1978; p->Month. Of. Birth = 12; p->Day. Of. Birth = 24;

More on Arrow Operator structoperator Personal. Data friend, Dot (. ) for *p; structure variables pstruct = &friend; Personal. Data friend; strcpy((*p). name, "George Lin"); strcpy(friend. name, "George Lin"); strcpy((*p). address, "Taipei Taiwan"); strcpy(friend. address, "Taipei Taiwan"); (*p). Year. Of. Birth = 1978; friend. Year. Of. Birth = 1978; (*p). friend. Month. Of. Birth = 12; (*p). Day. Of. Birth = 24; friend. Day. Of. Birth = 24; l Arrow operator (->) for pointers struct Personal. Data friend, *p; p = &friend; strcpy(p->name, "George Lin"); strcpy(p->address, "Taipei Taiwan"); p->Year. Of. Birth = 1978; p->friend. Month. Of. Birth = 12; p->Day. Of. Birth = 24; equivalent l

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Using Structures with Functions

Parameter Passings l typedef struct _tag. Complex { double real; double imag; } Complex; Passing Value Complex Add. By. Val(Complex a, Complex b); l Passing Reference void Add. By. Ref(const Complex *a, const Complex *b, Complex *c);

Example // complex. h typedef struct _tag. Complex { double real; double imag; } Complex; Complex Add. By. Val(Complex, Complex); void Add. By. Ref(Complex*, Complex*); // complex. c #include "complex. h" Complex Add. By. Val(Complex a, Complex b) { Complex c; c. real = a. real + b. real; c. imag = a. imag + b. imag; return c; } void Add. By. Ref(Complex* a, Complex* b, Complex* c) { c->real = a->real + b->real; c->imag = a->imag + b->imag; }

Example // complex. h typedef struct _tag. Complex { double real; double imag; } Complex; Complex Add. By. Val(Complex, Complex); void Add. By. Ref(Complex*, Complex*); // main. c #include <stdio. h> // complex. c #include "complex. h" main() Complex Add. By. Val(Complex a, Complex b) { { Complex x = {12. 0, 5}; Complex c; Complex y = {4. 0, 8. 0}; Complex z, w; c. real = a. real + b. real; c. imag = a. imag + b. imag; // Call by value z = Add. By. Val(x, y); return c; printf("(%. 1 f + i%. 1 f) + (%. 1 f + i%. 1 f) = (%. 1 f + i%. 1 f)n", } x. real, x. imag, y. real, y. imag, z. real, z. imag); void Add. By. Ref(Complex* a, Complex* b, Complex* c) // Call by reference { Add. By. Ref(&x, &y , &w); c->real = a->real + b->real; printf("(%. 1 f + i%. 1 f) + (%. 1 f + i%. 1 f) = (%. 1 f + i%. 1 f)n", c->imag = a->imag + b->imag; x. real, x. imag, y. real, y. imag, w. real, w. imag); } }

Passing arrays by value l l Create a structure with the array as a member Pass the structure

C Program Design C Structures, Unions, Bit Manipulations and Enumerations typedef

typedef type-declaration synonym; l l l Creates synonyms for previously defined data types – typedef does not create a new data type – Only creates an alias Create shorter type names Make a program more portable.

Example // complex. h struct _tag. Complex { double real; double imag; }; typedef struct _tag. Complex; typedef struct _tag. Complex *ptr. Complex; Complex Add. By. Val(Complex, Complex); void Add. By. Ref(ptr. Complex, ptr. Complex);

Some More Examples // Some. Type. Def. h #include "complex. h" typedef char CHAR; typedef CHAR* PSTR; typedef unsigned char BYTE; // complex. h struct _tag. Complex { double real; double imag; }; typedef struct _tag. Complex; typedef struct _tag. Complex *ptr. Complex; Complex Add. By. Val(Complex, Complex); void Add. By. Ref(ptr. Complex, ptr. Complex); typedef int INT; typedef unsigned UINT; typedef UINT DWORD; typedef Complex (*COMPLEXOP)(Complex, Complex); typedef INT (*ARITHOP)(INT, INT); INT INT sum(INT a, INT b); substract(INT a, INT b); mul(INT a, INT b); div(INT a, INT b);

/* arith. c */ Some More Examples #include <Some. Typedef. h> INT sum(INT a, INT b) { return a + b; } INT substract(INT a, INT b) // complex. h struct _tag. Complex { double real; double imag; }; typedef struct _tag. Complex; typedef struct _tag. Complex *ptr. Complex; { return a - b; } INT mul(INT a, INT b) { return a * b; } // Some. Type. Def. h #include "complex. h" typedef char CHAR; typedef CHAR* PSTR; typedef unsigned char BYTE; typedef int INT; typedef unsigned UINT; typedef UINT DWORD; INT div(INT a, INT b) { if(b) return a / b; else return 0; } Complex Add. By. Val(Complex, Complex); void Add. By. Ref(ptr. Complex, ptr. Complex); typedef Complex (*COMPLEXOP)(Complex, Complex); typedef INT (*ARITHOP)(INT, INT); INT INT sum(INT a, INT b); substract(INT a, INT b); mul(INT a, INT b); div(INT a, INT b);
![Some More Examples #include <stdio. h> ARITHOP arith[4]={sum, substract, mul, div}; // complex. h Some More Examples #include <stdio. h> ARITHOP arith[4]={sum, substract, mul, div}; // complex. h](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-42.jpg)
Some More Examples #include <stdio. h> ARITHOP arith[4]={sum, substract, mul, div}; // complex. h struct _tag. Complex { double real; double imag; }; main() typedef struct _tag. Complex; typedef struct _tag. Complex *ptr. Complex; #include "Some. Typedef. h" { INT val 1, val 2, op; Complex Add. By. Val(Complex, Complex); void Add. By. Ref(ptr. Complex, ptr. Complex); printf("Enter two numbers: "); // Some. Type. Def. h #include "complex. h" scanf("%d %d", &val 1, &val 2); printf("0: Add, 1: Sub, 2: Mul, 3: Divn"); do { printf("Enter number of operation: "); scanf("%d", &op); } while(op<0 || op>3); printf("%d", (*arith[op])(val 1, val 2)); } typedef char CHAR; typedef CHAR* PSTR; typedef unsigned char BYTE; typedef int INT; typedef unsigned UINT; typedef UINT DWORD; typedef Complex (*COMPLEXOP)(Complex, Complex); typedef INT (*ARITHOP)(INT, INT); INT INT sum(INT a, INT b); substract(INT a, INT b); mul(INT a, INT b); div(INT a, INT b);
![Some More Examples #include <stdio. h> ARITHOP arith[4]={sum, substract, mul, div}; // complex. h Some More Examples #include <stdio. h> ARITHOP arith[4]={sum, substract, mul, div}; // complex. h](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-43.jpg)
Some More Examples #include <stdio. h> ARITHOP arith[4]={sum, substract, mul, div}; // complex. h struct _tag. Complex { double real; double imag; }; main() typedef struct _tag. Complex; typedef struct _tag. Complex *ptr. Complex; #include "Some. Typedef. h" { INT val 1, val 2, op; Complex Add. By. Val(Complex, Complex); void Add. By. Ref(ptr. Complex, ptr. Complex); printf("Enter two numbers: "); // Some. Type. Def. h #include "complex. h" scanf("%d %d", &val 1, &val 2); printf("0: Add, 1: Sub, 2: Mul, 3: Divn"); do { printf("Enter number of operation: "); scanf("%d", &op); } while(op<0 || op>3); printf("%d", (*arith[op])(val 1, val 2)); } typedef char CHAR; typedef CHAR* PSTR; typedef unsigned char BYTE; typedef int INT; typedef unsigned UINT; typedef UINT DWORD; typedef Complex (*COMPLEXOP)(Complex, Complex); typedef INT (*ARITHOP)(INT, INT); INT INT sum(INT a, INT b); substract(INT a, INT b); mul(INT a, INT b); div(INT a, INT b);

Exercise 1. Implement a program similar to the above example but for complex numbers.

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Unions

union l l It is sometimes desirable to define a variable which can be of two or more different types according to different circumstances (overloading). The distinction between a union and a structure: – – l The members of a structure define different variables The members of a union define different manifestations of the same variable. The space need only be allocated to accommodate the largest type specified in a union.
![union Definition union Remark { int age; double tall; char month[4]; } rem; union union Definition union Remark { int age; double tall; char month[4]; } rem; union](http://slidetodoc.com/presentation_image_h2/cfb61c9bcb98b9e11e6af80a115cbc8e/image-47.jpg)
union Definition union Remark { int age; double tall; char month[4]; } rem; union Remark { int age; double tall; char month[4]; }; union Remark rem; typedef union _tag. Remark { int age; double tall; char month[4]; } REMARK; REMARK rem; sizeof(union Remark)=? sizeof(REMARK)=?

Valid union Operations l l Assignment to union of same type: = x = y; y = *p; union Remark { Taking address: & int age; double tall; p = &x; char month[4]; Accessing union members: . } x, y, *p; int n = x. age; printf("%sn", y. month); Accessing members using pointers: -> int m = p->age; printf("%sn", p->month);

Example // remark. h typedef union _tag. Remark { int age; double tall; char month[4]; } REMARK; typedef struct _tag. Var. Remark { int type. Remark; // 0: age // 1: tall // 2: month REMARK rem; } Var. Remark; // main. c #include <stdio. h> #include <string. h> #include "remark. h" void Show. Data(Var. Remark data) { switch(data. type. Remark){ case 0: printf("Age = %dn", data. rem. age); break; case 1: printf("Tall = %fn", data. rem. tall); break; case 2: printf("Month = %sn", data. rem. month); break; } A union may only be initialized with a } value of the type of its first member. main() { Var. Remark datas[3]={{0, 35}, {1}, {2}}; int i; datas[1]. rem. tall = 174. 5; strcpy(datas[2]. rem. month, "Jul"); for(i=0; i< sizeof(datas) / sizeof(Var. Remark); i++) Show. Data(datas[i]); }

Example // remark. h typedef union _tag. Remark { int age; double tall; char month[4]; } REMARK; typedef struct _tag. Var. Remark { int type. Remark; // 0: age // 1: tall // 2: month REMARK rem; } Var. Remark; // main. c #include <stdio. h> #include <string. h> #include "remark. h" void Show. Data(Var. Remark data) { switch(data. type. Remark){ case 0: printf("Age = %dn", data. rem. age); break; case 1: printf("Tall = %fn", data. rem. tall); break; case 2: printf("Month = %sn", data. rem. month); break; } } main() { Var. Remark datas[3]={{0, 35}, {1}, {2}}; int i; datas[1]. rem. tall = 174. 5; strcpy(datas[2]. rem. month, "Jul"); for(i=0; i< sizeof(datas) / sizeof(Var. Remark); i++) Show. Data(datas[i]); }

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Bitwise Operators

Bits l All data is represented internally as sequences of bits – – l Each bit can be either 0 or 1 Sequence of 8 bits forms a byte What operations needed?

Bitwise Operators

Example (I) // display. Bits. c void display. Bits( unsigned value ) { unsigned c; // counter unsigned display. Mask = 1 << 31; // display. Mask printf( "%10 u = ", value ); for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & display. Mask ? '1' : '0' ); value <<= 1; // shift value left by 1 // output space per 8 bits if ( c % 8 == 0 ) putchar( ' ' ); } /* end for */ putchar( 'n' ); } /* end function display. Bits */

Example (I) // main. c #include <stdio. h> // display. Bits. c void display. Bits( unsigned value ); // prototype void display. Bits( unsigned value ) int main( void ) { unsigned c; // counter { unsigned // variable to hold user input unsigned display. Mask = 1 << 31; // x; display. Mask while(1){ printf( "%10 u = ", value ); printf( "Enter an unsigned integer: " ); scanf( &x ); for ( c = 1; c <= 32; c++ ) {// loop"%u", through bits putchar( value & display. Mask ? '1' : '0' ); display. Bits( value <<= 1; // shift value left by 1 x ); } // output space per 8 bits if ( c % 8 == 0 ) putchar( ' ' ); return 0; // indicates successful termination } /* end for */ } /* end main */ putchar( 'n' ); } /* end function display. Bits */

Example (I) // main. c #include <stdio. h> // display. Bits. c void display. Bits( unsigned value ); // prototype void display. Bits( unsigned value ) int main( void ) { unsigned c; // counter { unsigned // variable to hold user input unsigned display. Mask = 1 << 31; // x; display. Mask while(1){ printf( "%10 u = ", value ); printf( "Enter an unsigned integer: " ); scanf( &x ); for ( c = 1; c <= 32; c++ ) {// loop"%u", through bits putchar( value & display. Mask ? '1' : '0' ); display. Bits( value <<= 1; // shift value left by 1 x ); } // output space per 8 bits if ( c % 8 == 0 ) putchar( ' ' ); return 0; // indicates successful termination } /* end for */ } /* end main */ putchar( 'n' ); } /* end function display. Bits */

Example (II) // display. Bits. c void display. Bits( char* heading, unsigned value ) { unsigned c; // counter unsigned display. Mask = 1 << 31; // display. Mask printf( "%8 s", heading ); for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & display. Mask ? '1' : '0' ); value <<= 1; // shift value left by 1 // output space per 8 bits if ( c % 8 == 0 ) putchar( ' ' ); } /* end for */ putchar( 'n' ); } /* end function display. Bits */

// main. c #include <stdio. h> Example (II) void display. Bits( char*, unsigned ); // prototype // display. Bits. c int main( void ) { unsigned x, y; // variable to hold user input void display. Bits( char* while(1){ heading, unsigned value ) { printf( "Enter two unsigned integers in hex. : " ); unsigned c; // counter scanf( "%x %x", &x, &y ); unsigned display. Mask = 1 << 31; // display. Mask display. Bits( "x =", x ); printf( "%8 s", heading ); display. Bits( "y =", y ); for ( c = 1; c <= 32; c++ ) {// loop "~x through bits display. Bits( =", ~x ); putchar( value & display. Mask ? '1' : '0' ); display. Bits( "~y =", ~y ); value <<= 1; // shift value left by 1 // output space per 8 display. Bits( bits "x & y =", x & y); if ( c % 8 == 0 ) putchar( ' ' ); display. Bits( "x | y =", x | y); } /* end for */ display. Bits( "x ^ y =", x ^ y); putchar( 'n' ); printf("n"); } /* end function display. Bits */ } } /* end main */

// main. c #include <stdio. h> Example (II) void display. Bits( char*, unsigned ); // prototype // display. Bits. c int main( void ) { unsigned x, y; // variable to hold user input void display. Bits( char* while(1){ heading, unsigned value ) { printf( "Enter two unsigned integers in hex. : " ); unsigned c; // counter scanf( "%x %x", &x, &y ); unsigned display. Mask = 1 << 31; // display. Mask display. Bits( "x =", x ); printf( "%8 s", heading ); display. Bits( "y =", y ); for ( c = 1; c <= 32; c++ ) {// loop "~x through bits display. Bits( =", ~x ); putchar( value & display. Mask ? '1' : '0' ); display. Bits( "~y =", ~y ); value <<= 1; // shift value left by 1 // output space per 8 display. Bits( bits "x & y =", x & y); if ( c % 8 == 0 ) putchar( ' ' ); display. Bits( "x | y =", x | y); } /* end for */ display. Bits( "x ^ y =", x ^ y); putchar( 'n' ); printf("n"); } /* end function display. Bits */ } } /* end main */

Bitwise Assignment Operators

Operator precedence and associativity

Operator precedence and associativity

Exercise: On-Off Bits Counting Write a pair of functions, bitson and bitsoff, that return the number of bits that are on and off in a file. Use the shorthand bit -manipulation operators.

Exercise: On-Off Bits Counting Example: Boy. txt Good boy. G o o d b o y. 0100 0110 0010 0110 0111 0010 0111 1111 0100 0010 1111 1001 1110 on off 4 4 6 2 3 5 1 7 3 5 6 2 5 3 4 4 38 34

Exercise: On-Off Bits Counting Example: on G o o d off 4 4 0111 6 2 1111 3 5 0100 1 7 0000 3 5 0010 6 2 1111 off-bits 5 in file 3 Boy. txt. 1001 4 4 0010 1110 0100 0110 Boy. txt 0110 0010 b 0110 o 0110 There are 38 on-bits yand 34 0111 Good boy. . 38 34

Exercise: On-Off Bits Counting mask 01101110 & 10000000 On Off mask On Off 01101110 & 01000000 01101110 & 00100000 01101110 & 00010000 01101110 & 00001000 & 00000100 & 00000010 & 00000001 0000

Exercise: On-Off Bits Counting l int bitson(char c) returns number of on-bit in c l int bitsoff(char c) returns number of off-bit in c

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Bit Fields

Why Bit Fields? sizeof(struct Card) = ? struct Card { unsigned face; unsigned suit; unsigned color; };

Bit Fields l When storage space is at a premium, it may be necessary to pack several objects into a single machine storage unit. suit color face

Defining Bit Fields struct Bit. Card { unsigned face : 4; unsigned suit : 2; unsigned color: 1; }; sizeof(struct Bit. Card) = ? suit color face

Defining Bit Fields struct Bit. Card { unsigned face : 4; unsigned suit : 2; unsigned color: 1; }; l Follow unsigned or int member with a colon (: ) and an integer constant representing the width of the field.

Example // Cards. h // bit. Card structure definition with bit fields struct bit. Card { unsigned face : 4; // 4 bits; 0 -15 unsigned suit : 2; // 2 bits; 0 -3 unsigned color : 1; // 1 bit; 0 -1 }; // end struct bit. Card typedef struct bit. Card; // new type name for struct bit. Card void fill. Deck( Card * const w. Deck ); // prototype void deal( const Card * const w. Deck ); // prototype

// Cards. h Example #include <stdio. h> #include "Cards. h" void fill. Deck( Card * const w. Deck ) { int i; /* counter */ for ( i = w. Deck[ } // bit. Card structure definition with bit fields struct bit. Card { unsigned face : 4; // 4 bits; 0 -15 unsigned suit : 2; // 2 bits; 0 -3 unsigned color : 1; // 1 bit; 0 -1 }; // end struct bit. Card typedef struct bit. Card; // new type name for struct bit. Card void fill. Deck( Card * const w. Deck ); // prototype void deal( const Card * const w. Deck ); // prototype 0; i <= 51; i++ ) { i ]. face = i % 13; i ]. suit = i / 13; i ]. color = i / 26; } void deal( const Card * const w. Deck ) { int k 1; /* subscripts 0 -25 */ int k 2; /* subscripts 26 -51 */ for ( k 1 = 0, k 2 = k 1 + 26; k 1 <= 25; k 1++, k 2++ ) { printf( "Card: %3 d Suit: %2 d Color: %2 d ", w. Deck[ k 1 ]. face, w. Deck[ k 1 ]. suit, w. Deck[ k 1 ]. color ); printf( "Card: %3 d Suit: %2 d Color: %2 dn", w. Deck[ k 2 ]. face, w. Deck[ k 2 ]. suit, w. Deck[ k 2 ]. color ); } }

// Cards. h Example #include <stdio. h> #include "Cards. h" void fill. Deck( Card * const w. Deck ) { int i; /* counter */ // bit. Card structure definition with bit fields struct bit. Card { unsigned face : 4; // 4 bits; 0 -15 unsigned suit : 2; // 2 bits; 0 -3 unsigned color : 1; // 1 bit; 0 -1 }; // end struct bit. Card typedef struct bit. Card; // new type name for struct bit. Card void fill. Deck( Card * const w. Deck ); // prototype void deal( const Card * const w. Deck ); // prototype // for (main. c i = 0; i <= 51; i++ ) { w. Deck[ i ]. face = i % 13; #include <stdio. h> w. Deck[ i ]. suit = i / 13; w. Deck[ i ]. color = i / 26; #include "Cards. h“ } } int main( void ) { Card deck[ 52 ]; // create array of Cards void deal( const Card * const w. Deck ) { int k 1; /* subscripts 0 -25 */ int k 2; /* subscripts 26 -51 */ for ( k 1 = 0, k 2 = k 1 + 26; k 1 <= 25; k 1++, k 2++ ) { printf( "Card: %3 d Suit: %2 d Color: %2 d ", w. Deck[ k 1 ]. face, w. Deck[ k 1 ]. suit, w. Deck[ k 1 ]. color ); printf( "Card: %3 d Suit: %2 d Color: %2 dn", w. Deck[ k 2 ]. face, w. Deck[ k 2 ]. suit, w. Deck[ k 2 ]. color ); } fill. Deck( deck ); deal( deck ); } }

// Cards. h Example #include <stdio. h> #include "Cards. h" void fill. Deck( Card * const w. Deck ) { int i; /* counter */ for ( i = w. Deck[ } 0; i <= 51; i++ ) { i ]. face = i % 13; i ]. suit = i / 13; i ]. color = i / 26; // bit. Card structure definition with bit fields struct bit. Card { unsigned face : 4; // 4 bits; 0 -15 unsigned suit : 2; // 2 bits; 0 -3 unsigned color : 1; // 1 bit; 0 -1 }; // end struct bit. Card typedef struct bit. Card; // new type name for struct bit. Card void fill. Deck( Card * const w. Deck ); // prototype void deal( const Card * const w. Deck ); // prototype // main. c #include <stdio. h> #include "Cards. h“ int main( void ) { Card deck[ 52 ]; // create array of Cards fill. Deck( deck ); deal( deck ); } void deal( const Card * const w. Deck ) { int k 1; /* subscripts 0 -25 */ int k 2; /* subscripts 26 -51 */ } for ( k 1 = 0, k 2 = k 1 + 26; k 1 <= 25; k 1++, k 2++ ) { printf( "Card: %3 d Suit: %2 d Color: %2 d ", w. Deck[ k 1 ]. face, w. Deck[ k 1 ]. suit, w. Deck[ k 1 ]. color ); printf( "Card: %3 d Suit: %2 d Color: %2 dn", w. Deck[ k 2 ]. face, w. Deck[ k 2 ]. suit, w. Deck[ k 2 ]. color ); } }

More on Defining Bit Fields l Unnamed bit field – Field used as padding in the structure – Nothing may be stored in the bits struct Un. Name. Example { unsigned a : 13; unsigned : 3; // unnamed unsigned b : 4; }; – Unnamed bit field with zero width aligns next bit field to a new storage unit boundary

Example struct Unname. Example { /* field 4 bits wide */ unsigned field 1 : 4; /* unnamed 3 bit field * unnamed fields allow for padding */ unsigned : 3; /* one-bit field * can only be 0 or -1 in two's complement! */ signed field 2 : 1; /* align next field on a storage unit */ unsigned : 0; unsigned field 3 : 6; };

C Program Design C Structures, Unions, Bit Manipulations and Enumerations Enumeration Constants

Enumeration enum Suits {CLUB, DIMOND, SPADE, HEART}; enum Months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; l l l Set of integer constants represented by identifiers Enumeration constants are like symbolic constants whose values are automatically set Need unique constant names Values start at 0 and are incremented by 1 Values can be set explicitly with =

Enumeration enum Suits {CLUB, DIMOND, SPADE, HEART}; enum Months {JAN, {JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; l l l Set of integer constants represented by identifiers Enumeration constants are like symbolic constants whose values are automatically set Need unique constant names Values start at 0 and are incremented by 1 Values can be set explicitly with =

Example #include <stdio. h> enum months {// enumeration constants represent months of the year JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; int main( void ) { enum months month; // can contain any of the 12 months const char *month. Name[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for ( month = JAN; month <= DEC; month++ ) printf( "%2 d%11 sn", month. Name[ month ] ); }

Example #include <stdio. h> enum months {// enumeration constants represent months of the year JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; int main( void ) { enum months month; // can contain any of the 12 months const char *month. Name[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for ( month = JAN; month <= DEC; month++ ) printf( "%2 d%11 sn", month. Name[ month ] ); }

More Examples enum boolean { NO, YES }; enum escapes { BELL = 'a', BACKSPACE = 'b', TAB = 't', NEWLINE = 'n', VTAB = 'v', RETURN = 'r' }; enum Action {stop = 1, sit, stand = 2, walk, run}; // sit = stand =2 enum Action action = stop; // initializaiton printf("%dn", action + 2); Action--; // operation
- Slides: 84