c program design c structures, unions, bit manipulations and enumerations

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

Upload: alfonso-valentine

Post on 30-Dec-2015

49 views

Category:

Documents


6 download

DESCRIPTION

C Program Design C Structures, Unions, Bit Manipulations and Enumerations. 主講人:虞台文. Content. Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions typedef Unions Bitwise Operators Bit Fields Enumeration Constants. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

主講人:虞台文

Page 2: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

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

Page 3: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Introduction

Page 4: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Main Topics

Structure– 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 Union

– Allowed data type being overloaded Bit fields Enumeration

Page 5: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Structure Definitions

Page 6: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Structure Definitions

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

A structure definition does not reserve space in memory.

Instead, creates a new data type used to define structure variables.

Page 7: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Define Structure Variables (I)

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData teacher, students[51], *p;

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData teacher, students[51], *p;

Page 8: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData teacher, students[51], *p;

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData teacher, students[51], *p;

Define Structure Variables (II)

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;} teacher, students[51], *p;// variable identifier follows type

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;} teacher, students[51], *p;// variable identifier follows type

Page 9: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData teacher, students[51], *p;

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData teacher, students[51], *p;

Define Structure Variables (III)

struct PersonalData{ char name[namesize]; char address[addresssize]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;} teacher, students[51], *p;// variable identifier follows type

struct PersonalData{ char name[namesize]; char address[addresssize]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;} teacher, students[51], *p;// variable identifier follows type

typedef struct _tagPersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;} PersonalData;

PersonalData teacher, students[51], *p;

typedef struct _tagPersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;} PersonalData;

PersonalData teacher, students[51], *p;

Page 10: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Valid Operations

Assigning a structure to a structure of the same typex = teacher;teacher = *p;students[i] = x;

Taking the address (&) of a structure p = &students[i];

Accessing the members of a structuregets(students[0].name);p->YearOfBirth = 88;

Using the sizeof to determine the size of a structuresize = sizeof(struct PersonalData);size = sizeof(x);

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData x, teacher, students[51], *p;

struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

struct PersonalData x, teacher, students[51], *p;

Page 11: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

#include <stdio.h>

#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

main(){ struct PersonalData 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("%2d/%2d/%2d", &student.YearOfBirth,

&student.MonthOfBirth, &student.DayOfBirth);

printf("\n\n");

// Print out the student record printf("Student name: %s\n", student.name); printf("Address: %s\n", student.address); printf("Bithday: %2d/%2d/%2d\n", student.YearOfBirth, student.MonthOfBirth, student.DayOfBirth);}

#include <stdio.h>

#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

main(){ struct PersonalData 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("%2d/%2d/%2d", &student.YearOfBirth,

&student.MonthOfBirth, &student.DayOfBirth);

printf("\n\n");

// Print out the student record printf("Student name: %s\n", student.name); printf("Address: %s\n", student.address); printf("Bithday: %2d/%2d/%2d\n", student.YearOfBirth, student.MonthOfBirth, student.DayOfBirth);}

Page 12: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

#include <stdio.h>

#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

main(){ struct PersonalData 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("%2d/%2d/%2d", &student.YearOfBirth,

&student.MonthOfBirth, &student.DayOfBirth);

printf("\n\n");

// Print out the student record printf("Student name: %s\n", student.name); printf("Address: %s\n", student.address); printf("Bithday: %2d/%2d/%2d\n", student.YearOfBirth, student.MonthOfBirth, student.DayOfBirth);}

#include <stdio.h>

#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

main(){ struct PersonalData 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("%2d/%2d/%2d", &student.YearOfBirth,

&student.MonthOfBirth, &student.DayOfBirth);

printf("\n\n");

// Print out the student record printf("Student name: %s\n", student.name); printf("Address: %s\n", student.address); printf("Bithday: %2d/%2d/%2d\n", student.YearOfBirth, student.MonthOfBirth, student.DayOfBirth);}

Page 13: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

#include <stdio.h>

#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

main(){ struct PersonalData 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("%2d/%2d/%2d", &student.YearOfBirth,

&student.MonthOfBirth, &student.DayOfBirth);

printf("\n\n");

// Print out the student record printf("Student name: %s\n", student.name); printf("Address: %s\n", student.address); printf("Bithday: %2d/%2d/%2d\n", student.YearOfBirth, student.MonthOfBirth, student.DayOfBirth);}

#include <stdio.h>

#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

main(){ struct PersonalData 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("%2d/%2d/%2d", &student.YearOfBirth,

&student.MonthOfBirth, &student.DayOfBirth);

printf("\n\n");

// Print out the student record printf("Student name: %s\n", student.name); printf("Address: %s\n", student.address); printf("Bithday: %2d/%2d/%2d\n", student.YearOfBirth, student.MonthOfBirth, student.DayOfBirth);}

getPersonInfo(&student);

showPersonInfo(&student);

Page 14: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student;

// Enter the student's record getPersonInfo(&student);

printf("\n\n");

// Print out the student record showPersonInfo(&student);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student;

// Enter the student's record getPersonInfo(&student);

printf("\n\n");

// Print out the student record showPersonInfo(&student);}

Page 15: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student;

// Enter the student's record getPersonInfo(&student);

printf("\n\n");

// Print out the student record showPersonInfo(&student);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student;

// Enter the student's record getPersonInfo(&student);

printf("\n\n");

// Print out the student record showPersonInfo(&student);}

Example// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

Page 16: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student;

// Enter the student's record getPersonInfo(&student);

printf("\n\n");

// Print out the student record showPersonInfo(&student);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student;

// Enter the student's record getPersonInfo(&student);

printf("\n\n");

// Print out the student record showPersonInfo(&student);}

Page 17: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

sizeof Operator

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

sizeof(struct SomeData) = ?

Page 18: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

sizeof Operator

#include <stdio.h>#include <limits.h>#include <float.h>

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

main(){ char mark[]={'M', 'A', 'R', 'K'}; struct SomeData x;

printf("sizeof(struct SomeData) = %d\n\n", sizeof(struct SomeData));

x.aChar = 'A'; x.anInt = INT_MAX; x.aFloat = FLT_MAX; x.aDouble = DBL_MAX;

printf("Address of x: %p\n", &x); printf("Address of x.aChar: %p\n", &x.aChar); printf("Address of x.anInt: %p\n", &x.anInt); printf("Address of x.aFloat: %p\n", &x.aFloat); printf("Address of x.aDouble: %p\n", &x.aDouble);}

#include <stdio.h>#include <limits.h>#include <float.h>

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

main(){ char mark[]={'M', 'A', 'R', 'K'}; struct SomeData x;

printf("sizeof(struct SomeData) = %d\n\n", sizeof(struct SomeData));

x.aChar = 'A'; x.anInt = INT_MAX; x.aFloat = FLT_MAX; x.aDouble = DBL_MAX;

printf("Address of x: %p\n", &x); printf("Address of x.aChar: %p\n", &x.aChar); printf("Address of x.anInt: %p\n", &x.anInt); printf("Address of x.aFloat: %p\n", &x.aFloat); printf("Address of x.aDouble: %p\n", &x.aDouble);}

Page 19: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

sizeof Operator

#include <stdio.h>#include <limits.h>#include <float.h>

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

main(){ char mark[]={'M', 'A', 'R', 'K'}; struct SomeData x;

printf("sizeof(struct SomeData) = %d\n\n", sizeof(struct SomeData));

x.aChar = 'A'; x.anInt = INT_MAX; x.aFloat = FLT_MAX; x.aDouble = DBL_MAX;

printf("Address of x: %p\n", &x); printf("Address of x.aChar: %p\n", &x.aChar); printf("Address of x.anInt: %p\n", &x.anInt); printf("Address of x.aFloat: %p\n", &x.aFloat); printf("Address of x.aDouble: %p\n", &x.aDouble);}

#include <stdio.h>#include <limits.h>#include <float.h>

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

main(){ char mark[]={'M', 'A', 'R', 'K'}; struct SomeData x;

printf("sizeof(struct SomeData) = %d\n\n", sizeof(struct SomeData));

x.aChar = 'A'; x.anInt = INT_MAX; x.aFloat = FLT_MAX; x.aDouble = DBL_MAX;

printf("Address of x: %p\n", &x); printf("Address of x.aChar: %p\n", &x.aChar); printf("Address of x.anInt: %p\n", &x.anInt); printf("Address of x.aFloat: %p\n", &x.aFloat); printf("Address of x.aDouble: %p\n", &x.aDouble);}

Page 20: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

sizeof Operator

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

struct SomeData{ char aChar; int anInt; float aFloat; double aDouble;};

sizeof(struct SomeData) = ?

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.

Page 21: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Initializing Structures

Page 22: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

Page 23: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student = {

"Hale-Evans, Ron","Seattle, Washington",1965,6,27

};

// Print out the student record showPersonInfo(&student);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData student = {

"Hale-Evans, Ron","Seattle, Washington",1965,6,27

};

// Print out the student record showPersonInfo(&student);}

Page 24: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

}; struct PersonalData *p; int i; // Print out the records for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){ ShowPersonInfo(p++); printf("\n"); }}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

}; struct PersonalData *p; int i; // Print out the records for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){ ShowPersonInfo(p++); printf("\n"); }}

Page 25: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

}; struct PersonalData *p; int i; // Print out the records for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){ ShowPersonInfo(p++); printf("\n"); }}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

}; struct PersonalData *p; int i; // Print out the records for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){ ShowPersonInfo(p++); printf("\n"); }}

Page 26: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.h#define NAMESIZE 50#define ADDRSIZE 80struct PersonalData{ char name[NAMESIZE]; char address[ADDRSIZE]; int YearOfBirth; int MonthOfBirth; int DayOfBirth;};

void getPersonInfo(struct PersonalData *);void showPersonInfo(struct PersonalData *);

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// person.c#include <stdio.h>#include "person.h"

void getPersonInfo(struct PersonalData *p){ printf("Enter name: "); gets(p->name); printf("Enter address: "); gets(p->address); printf("Enter birthday: yy/mm/dd: "); scanf("%2d/%2d/%2d", &p->YearOfBirth,

&p->MonthOfBirth, &p->DayOfBirth);}

void showPersonInfo(struct PersonalData *p){ printf("Name: %s\n", p->name); printf("Address: %s\n", p->address); printf("Bithday: %2d/%2d/%2d\n", p->YearOfBirth,

p->MonthOfBirth, p->DayOfBirth);}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

}; struct PersonalData *p; int i; // Print out the records for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){ ShowPersonInfo(p++); printf("\n"); }}

// main.c#include <stdio.h>#include "person.h"

main(){ struct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

}; struct PersonalData *p; int i; // Print out the records for(i = 0, p = persons; i < sizeof(persons)/sizeof(struct PersonalData); i++){ ShowPersonInfo(p++); printf("\n"); }}

Page 27: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Initializing Structures

// initialized when definedstruct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

};

struct PersonalData classLeader, friend; // initialized using assignment operatorclassLeader = persons[1];

// Initialized field by fieldstrcpy(friend.name, "George Lin");strcpy(friend.address, "Taipei Taiwan");friend.YearOfBirth = 1978;friend.MonthOfBirth = 12;friend.DayOfBirth = 24;

// initialized when definedstruct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

};

struct PersonalData classLeader, friend; // initialized using assignment operatorclassLeader = persons[1];

// Initialized field by fieldstrcpy(friend.name, "George Lin");strcpy(friend.address, "Taipei Taiwan");friend.YearOfBirth = 1978;friend.MonthOfBirth = 12;friend.DayOfBirth = 24;

Page 28: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Initializing Structures

// initialized when definedstruct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

};

struct PersonalData classLeader, friend, *p; // initialized using assignment operatorclassLeader = persons[1];

// Initialized field by field using a pointerp = &friend;strcpy(p->name, "George Lin");strcpy(p->address, "Taipei Taiwan");p->YearOfBirth = 1978;p->MonthOfBirth = 12;p->DayOfBirth = 24;

// initialized when definedstruct PersonalData persons[] = {

{"Hale-Evans, Ron", "Seattle, Washington", 1965, 6, 27},{"Liddell, Alice", "Wonderland", 1852, 5, 4},{"Adams, Douglas", "The Galaxy", 1961, 11, 15}

};

struct PersonalData classLeader, friend, *p; // initialized using assignment operatorclassLeader = persons[1];

// Initialized field by field using a pointerp = &friend;strcpy(p->name, "George Lin");strcpy(p->address, "Taipei Taiwan");p->YearOfBirth = 1978;p->MonthOfBirth = 12;p->DayOfBirth = 24;

Page 29: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Accessing Members of Structures

Page 30: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Accessing structure members

Dot operator (.) for structure variablesstruct PersonalData friend;strcpy(friend.name, "George Lin");strcpy(friend.address, "Taipei Taiwan");friend.YearOfBirth = 1978;friend.MonthOfBirth = 12;friend.DayOfBirth = 24;

Arrow operator (->) for pointersstruct PersonalData friend, *p; p = &friend;strcpy(p->name, "George Lin");strcpy(p->address, "Taipei Taiwan");p->YearOfBirth = 1978;p->MonthOfBirth = 12;p->DayOfBirth = 24;

Page 31: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

More on Arrow Operator

Dot operator (.) for structure variablesstruct PersonalData friend;strcpy(friend.name, "George Lin");strcpy(friend.address, "Taipei Taiwan");friend.YearOfBirth = 1978;friend.MonthOfBirth = 12;friend.DayOfBirth = 24;

Arrow operator (->) for pointersstruct PersonalData friend, *p; p = &friend;strcpy(p->name, "George Lin");strcpy(p->address, "Taipei Taiwan");p->YearOfBirth = 1978;p->friend.MonthOfBirth = 12;p->DayOfBirth = 24;

struct PersonalData friend, *p; p = &friend;strcpy((*p).name, "George Lin");strcpy((*p).address, "Taipei Taiwan");(*p).YearOfBirth = 1978;(*p).friend.MonthOfBirth = 12;(*p).DayOfBirth = 24;

struct PersonalData friend, *p; p = &friend;strcpy((*p).name, "George Lin");strcpy((*p).address, "Taipei Taiwan");(*p).YearOfBirth = 1978;(*p).friend.MonthOfBirth = 12;(*p).DayOfBirth = 24;

eq

uiv

ale

nt

Page 32: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Using Structures

with Functions

Page 33: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

ParameterPassings

Passing Value

Complex AddByVal(Complex a, Complex b);

Passing Reference

void AddByRef(const Complex *a, const Complex *b,

Complex *c);

typedef struct _tagComplex{ double real; double imag;} Complex;

typedef struct _tagComplex{ double real; double imag;} Complex;

Page 34: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// complex.htypedef struct _tagComplex{ double real; double imag;} Complex;

Complex AddByVal(Complex, Complex);void AddByRef(Complex*, Complex*, Complex*);

// complex.htypedef struct _tagComplex{ double real; double imag;} Complex;

Complex AddByVal(Complex, Complex);void AddByRef(Complex*, Complex*, Complex*);

// complex.c#include "complex.h"

Complex AddByVal(Complex a, Complex b){ Complex c;

c.real = a.real + b.real; c.imag = a.imag + b.imag;

return c;}

void AddByRef(Complex* a, Complex* b, Complex* c){ c->real = a->real + b->real; c->imag = a->imag + b->imag;}

// complex.c#include "complex.h"

Complex AddByVal(Complex a, Complex b){ Complex c;

c.real = a.real + b.real; c.imag = a.imag + b.imag;

return c;}

void AddByRef(Complex* a, Complex* b, Complex* c){ c->real = a->real + b->real; c->imag = a->imag + b->imag;}

Page 35: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// complex.htypedef struct _tagComplex{ double real; double imag;} Complex;

Complex AddByVal(Complex, Complex);void AddByRef(Complex*, Complex*, Complex*);

// complex.htypedef struct _tagComplex{ double real; double imag;} Complex;

Complex AddByVal(Complex, Complex);void AddByRef(Complex*, Complex*, Complex*);

// complex.c#include "complex.h"

Complex AddByVal(Complex a, Complex b){ Complex c;

c.real = a.real + b.real; c.imag = a.imag + b.imag;

return c;}

void AddByRef(Complex* a, Complex* b, Complex* c){ c->real = a->real + b->real; c->imag = a->imag + b->imag;}

// complex.c#include "complex.h"

Complex AddByVal(Complex a, Complex b){ Complex c;

c.real = a.real + b.real; c.imag = a.imag + b.imag;

return c;}

void AddByRef(Complex* a, Complex* b, Complex* c){ c->real = a->real + b->real; c->imag = a->imag + b->imag;}

// main.c#include <stdio.h>#include "complex.h"

main(){ Complex x = {12.0, 5}; Complex y = {4.0, 8.0}; Complex z, w;

// Call by value z = AddByVal(x, y); printf("(%.1f + i%.1f) + (%.1f + i%.1f) = (%.1f + i%.1f)\n", x.real, x.imag, y.real, y.imag, z.real, z.imag);

// Call by reference AddByRef(&x, &y , &w); printf("(%.1f + i%.1f) + (%.1f + i%.1f) = (%.1f + i%.1f)\n", x.real, x.imag, y.real, y.imag, w.real, w.imag);}

// main.c#include <stdio.h>#include "complex.h"

main(){ Complex x = {12.0, 5}; Complex y = {4.0, 8.0}; Complex z, w;

// Call by value z = AddByVal(x, y); printf("(%.1f + i%.1f) + (%.1f + i%.1f) = (%.1f + i%.1f)\n", x.real, x.imag, y.real, y.imag, z.real, z.imag);

// Call by reference AddByRef(&x, &y , &w); printf("(%.1f + i%.1f) + (%.1f + i%.1f) = (%.1f + i%.1f)\n", x.real, x.imag, y.real, y.imag, w.real, w.imag);}

Page 36: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Passing arrays by value

Create a structure with the array as a member

Pass the structure

Page 37: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

typedef

Page 38: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

typedef

typedef type-declaration synonym;

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.

Page 39: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

Page 40: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Some More Examples// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

Page 41: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Some More Examples

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

/* arith.c */

#include <SomeTypedef.h>

INT sum(INT a, INT b)

{

return a + b;

}

INT substract(INT a, INT b)

{

return a - b;

}

INT mul(INT a, INT b)

{

return a * b;

}

INT div(INT a, INT b)

{

if(b) return a / b;

else return 0;

}

/* arith.c */

#include <SomeTypedef.h>

INT sum(INT a, INT b)

{

return a + b;

}

INT substract(INT a, INT b)

{

return a - b;

}

INT mul(INT a, INT b)

{

return a * b;

}

INT div(INT a, INT b)

{

if(b) return a / b;

else return 0;

}

Page 42: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Some More Examples

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

#include <stdio.h>

#include "SomeTypedef.h"

ARITHOP arith[4]={sum, substract, mul, div};

main()

{

INT val1, val2, op;

printf("Enter two numbers: ");

scanf("%d %d", &val1, &val2);

printf("0: Add, 1: Sub, 2: Mul, 3: Div\n");

do {

printf("Enter number of operation: ");

scanf("%d", &op);

} while(op<0 || op>3);

printf("%d", (*arith[op])(val1, val2));

}

#include <stdio.h>

#include "SomeTypedef.h"

ARITHOP arith[4]={sum, substract, mul, div};

main()

{

INT val1, val2, op;

printf("Enter two numbers: ");

scanf("%d %d", &val1, &val2);

printf("0: Add, 1: Sub, 2: Mul, 3: Div\n");

do {

printf("Enter number of operation: ");

scanf("%d", &op);

} while(op<0 || op>3);

printf("%d", (*arith[op])(val1, val2));

}

Page 43: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Some More Examples

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// SomeTypeDef.h#include "complex.h"

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 sum(INT a, INT b);INT substract(INT a, INT b);INT mul(INT a, INT b);INT div(INT a, INT b);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

// complex.hstruct _tagComplex{ double real; double imag;};

typedef struct _tagComplex Complex;typedef struct _tagComplex *ptrComplex;

Complex AddByVal(Complex, Complex);void AddByRef(ptrComplex, ptrComplex, ptrComplex);

#include <stdio.h>

#include "SomeTypedef.h"

ARITHOP arith[4]={sum, substract, mul, div};

main()

{

INT val1, val2, op;

printf("Enter two numbers: ");

scanf("%d %d", &val1, &val2);

printf("0: Add, 1: Sub, 2: Mul, 3: Div\n");

do {

printf("Enter number of operation: ");

scanf("%d", &op);

} while(op<0 || op>3);

printf("%d", (*arith[op])(val1, val2));

}

#include <stdio.h>

#include "SomeTypedef.h"

ARITHOP arith[4]={sum, substract, mul, div};

main()

{

INT val1, val2, op;

printf("Enter two numbers: ");

scanf("%d %d", &val1, &val2);

printf("0: Add, 1: Sub, 2: Mul, 3: Div\n");

do {

printf("Enter number of operation: ");

scanf("%d", &op);

} while(op<0 || op>3);

printf("%d", (*arith[op])(val1, val2));

}

Page 44: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Exercise

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

Page 45: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Unions

Page 46: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

union 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:– 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.

Page 47: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

union Definition

union Remark {int age;double tall;char month[4];

} rem;

union Remark {int age;double tall;char month[4];

} rem;

union Remark {int age;double tall;char month[4];

};

union Remark rem;

union Remark {int age;double tall;char month[4];

};

union Remark rem;

typedef union _tagRemark {int age;double tall;char month[4];

} REMARK;

REMARK rem;

typedef union _tagRemark {int age;double tall;char month[4];

} REMARK;

REMARK rem;

sizeof(union Remark)=?

sizeof(REMARK)=?

Page 48: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Valid union Operations

Assignment to union of same type: =x = y; y = *p;

Taking address: &p = &x;

Accessing union members: .int n = x.age;printf("%s\n", y.month);

Accessing members using pointers: ->int m = p->age;printf("%s\n", p->month);

union Remark {int age;double tall;char month[4];

} x, y, *p;

union Remark {int age;double tall;char month[4];

} x, y, *p;

Page 49: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example// main.c#include <stdio.h>#include <string.h>#include "remark.h"

void ShowData(VarRemark data){ switch(data.typeRemark){ case 0: printf("Age = %d\n", data.rem.age); break; case 1: printf("Tall = %f\n", data.rem.tall); break; case 2: printf("Month = %s\n", data.rem.month); break; }}

main(){ VarRemark 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(VarRemark); i++) ShowData(datas[i]);}

// main.c#include <stdio.h>#include <string.h>#include "remark.h"

void ShowData(VarRemark data){ switch(data.typeRemark){ case 0: printf("Age = %d\n", data.rem.age); break; case 1: printf("Tall = %f\n", data.rem.tall); break; case 2: printf("Month = %s\n", data.rem.month); break; }}

main(){ VarRemark 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(VarRemark); i++) ShowData(datas[i]);}

// remark.h

typedef union _tagRemark { int age; double tall; char month[4];} REMARK;

typedef struct _tagVarRemark { int typeRemark; // 0: age

// 1: tall // 2: month

REMARK rem;} VarRemark;

// remark.h

typedef union _tagRemark { int age; double tall; char month[4];} REMARK;

typedef struct _tagVarRemark { int typeRemark; // 0: age

// 1: tall // 2: month

REMARK rem;} VarRemark;

A union may only be initialized with a value of the type of its first

member.

A union may only be initialized with a value of the type of its first

member.

Page 50: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example// main.c#include <stdio.h>#include <string.h>#include "remark.h"

void ShowData(VarRemark data){ switch(data.typeRemark){ case 0: printf("Age = %d\n", data.rem.age); break; case 1: printf("Tall = %f\n", data.rem.tall); break; case 2: printf("Month = %s\n", data.rem.month); break; }}

main(){ VarRemark 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(VarRemark); i++) ShowData(datas[i]);}

// main.c#include <stdio.h>#include <string.h>#include "remark.h"

void ShowData(VarRemark data){ switch(data.typeRemark){ case 0: printf("Age = %d\n", data.rem.age); break; case 1: printf("Tall = %f\n", data.rem.tall); break; case 2: printf("Month = %s\n", data.rem.month); break; }}

main(){ VarRemark 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(VarRemark); i++) ShowData(datas[i]);}

// remark.h

typedef union _tagRemark { int age; double tall; char month[4];} REMARK;

typedef struct _tagVarRemark { int typeRemark; // 0: age

// 1: tall // 2: month

REMARK rem;} VarRemark;

// remark.h

typedef union _tagRemark { int age; double tall; char month[4];} REMARK;

typedef struct _tagVarRemark { int typeRemark; // 0: age

// 1: tall // 2: month

REMARK rem;} VarRemark;

Page 51: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Bitwise Operators

Page 52: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Bits

All data is represented internally as sequences of bits– Each bit can be either 0 or 1 – Sequence of 8 bits forms a byte

What operations needed?

Page 53: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Bitwise Operators

Operator Description

& bitwise AND The bits in the result are set to 1 if the corresponding bits in the two operands are both 1 .

| bitwise inclusive OR

The bits in the result are set to 1 if at least one of the corresponding bits in the two operands is 1.

^ bitwise exclusive OR

The bits in the result are set to 1 if exactly one of the corresponding bits in the two operands is 1.

<< left shift Shifts the bits of the first operand left by the number of bits specified by the second operand; fill from the right with 0 bits.

>> right shift Shifts the bits of the first operand right by the number of bits specified by the second operand; the method of filling from the left is machine dependent.

~ one’s complement All 0 bits are set to 1 and all 1 bits are set to 0.

Operator Description

& bitwise AND The bits in the result are set to 1 if the corresponding bits in the two operands are both 1 .

| bitwise inclusive OR

The bits in the result are set to 1 if at least one of the corresponding bits in the two operands is 1.

^ bitwise exclusive OR

The bits in the result are set to 1 if exactly one of the corresponding bits in the two operands is 1.

<< left shift Shifts the bits of the first operand left by the number of bits specified by the second operand; fill from the right with 0 bits.

>> right shift Shifts the bits of the first operand right by the number of bits specified by the second operand; the method of filling from the left is machine dependent.

~ one’s complement All 0 bits are set to 1 and all 1 bits are set to 0.

Page 54: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example (I)

// displayBits.c

void displayBits( unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%10u = ", value );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// displayBits.c

void displayBits( unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%10u = ", value );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

Page 55: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example (I)

// displayBits.c

void displayBits( unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%10u = ", value );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// displayBits.c

void displayBits( unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%10u = ", value );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// main.c#include <stdio.h>

void displayBits( unsigned value ); // prototype

int main( void ){ unsigned x; // variable to hold user input

while(1){ printf( "Enter an unsigned integer: " ); scanf( "%u", &x );

displayBits( x ); }

return 0; // indicates successful termination

} /* end main */

// main.c#include <stdio.h>

void displayBits( unsigned value ); // prototype

int main( void ){ unsigned x; // variable to hold user input

while(1){ printf( "Enter an unsigned integer: " ); scanf( "%u", &x );

displayBits( x ); }

return 0; // indicates successful termination

} /* end main */

Page 56: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example (I)

// displayBits.c

void displayBits( unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%10u = ", value );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// displayBits.c

void displayBits( unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%10u = ", value );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// main.c#include <stdio.h>

void displayBits( unsigned value ); // prototype

int main( void ){ unsigned x; // variable to hold user input

while(1){ printf( "Enter an unsigned integer: " ); scanf( "%u", &x );

displayBits( x ); }

return 0; // indicates successful termination

} /* end main */

// main.c#include <stdio.h>

void displayBits( unsigned value ); // prototype

int main( void ){ unsigned x; // variable to hold user input

while(1){ printf( "Enter an unsigned integer: " ); scanf( "%u", &x );

displayBits( x ); }

return 0; // indicates successful termination

} /* end main */

Page 57: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example (II)

// displayBits.c

void displayBits( char* heading, unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%8s", heading );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// displayBits.c

void displayBits( char* heading, unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%8s", heading );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

Page 58: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example (II)

// displayBits.c

void displayBits( char* heading, unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%8s", heading );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// displayBits.c

void displayBits( char* heading, unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%8s", heading );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// main.c#include <stdio.h>

void displayBits( char*, unsigned ); // prototype

int main( void ){ unsigned x, y; // variable to hold user input

while(1){ printf( "Enter two unsigned integers in hex.: " ); scanf( "%x %x", &x, &y );

displayBits( "x =", x ); displayBits( "y =", y );

displayBits( "~x =", ~x ); displayBits( "~y =", ~y );

displayBits( "x & y =", x & y); displayBits( "x | y =", x | y); displayBits( "x ^ y =", x ^ y);

printf("\n"); }} /* end main */

// main.c#include <stdio.h>

void displayBits( char*, unsigned ); // prototype

int main( void ){ unsigned x, y; // variable to hold user input

while(1){ printf( "Enter two unsigned integers in hex.: " ); scanf( "%x %x", &x, &y );

displayBits( "x =", x ); displayBits( "y =", y );

displayBits( "~x =", ~x ); displayBits( "~y =", ~y );

displayBits( "x & y =", x & y); displayBits( "x | y =", x | y); displayBits( "x ^ y =", x ^ y);

printf("\n"); }} /* end main */

Page 59: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example (II)

// displayBits.c

void displayBits( char* heading, unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%8s", heading );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// displayBits.c

void displayBits( char* heading, unsigned value ){ unsigned c; // counter unsigned displayMask = 1 << 31; // displayMask

printf( "%8s", heading );

for ( c = 1; c <= 32; c++ ) {// loop through bits putchar( value & displayMask ? '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 displayBits */

// main.c#include <stdio.h>

void displayBits( char*, unsigned ); // prototype

int main( void ){ unsigned x, y; // variable to hold user input

while(1){ printf( "Enter two unsigned integers in hex.: " ); scanf( "%x %x", &x, &y );

displayBits( "x =", x ); displayBits( "y =", y );

displayBits( "~x =", ~x ); displayBits( "~y =", ~y );

displayBits( "x & y =", x & y); displayBits( "x | y =", x | y); displayBits( "x ^ y =", x ^ y);

printf("\n"); }} /* end main */

// main.c#include <stdio.h>

void displayBits( char*, unsigned ); // prototype

int main( void ){ unsigned x, y; // variable to hold user input

while(1){ printf( "Enter two unsigned integers in hex.: " ); scanf( "%x %x", &x, &y );

displayBits( "x =", x ); displayBits( "y =", y );

displayBits( "~x =", ~x ); displayBits( "~y =", ~y );

displayBits( "x & y =", x & y); displayBits( "x | y =", x | y); displayBits( "x ^ y =", x ^ y);

printf("\n"); }} /* end main */

Page 60: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Bitwise Assignment Operators

Bitwise assignment operators

&= Bitwise AND assignment operator.

|= Bitwise inclusive OR assignment operator.

^= Bitwise exclusive OR assignment operator.

<<= Left-shift assignment operator.

>>= Right-shift assignment operator.

Bitwise assignment operators

&= Bitwise AND assignment operator.

|= Bitwise inclusive OR assignment operator.

^= Bitwise exclusive OR assignment operator.

<<= Left-shift assignment operator.

>>= Right-shift assignment operator.

Page 61: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Operator precedence and associativity

Operators Associativity Type

() [ ] . -> left to right highest

+ - ++ - ++ -- ! & * ~ sizeof (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

<< >> left to right shiting

< <= > >= left to right relational

== != left to right equality

& left to right bitwise AND

Operators Associativity Type

() [ ] . -> left to right highest

+ - ++ - ++ -- ! & * ~ sizeof (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

<< >> left to right shiting

< <= > >= left to right relational

== != left to right equality

& left to right bitwise AND

Page 62: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Operator precedence and associativity

Operators Associativity Type

() [ ] . -> left to right highest

+ - ++ - ++ -- ! & * ~ sizeof (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

<< >> left to right shiting

< <= > >= left to right relational

== != left to right equality

& left to right bitwise AND

Operators Associativity Type

() [ ] . -> left to right highest

+ - ++ - ++ -- ! & * ~ sizeof (type) right to left unary

* / % left to right multiplicative

+ - left to right additive

<< >> left to right shiting

< <= > >= left to right relational

== != left to right equality

& left to right bitwise AND

Operators Associativity Type

^ left to right bitwise OR

| left to right bitwise OR

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

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

, left to right comma

Operators Associativity Type

^ left to right bitwise OR

| left to right bitwise OR

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

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

, left to right comma

Page 63: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

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.

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.

Page 64: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Exercise: On-Off Bits Counting

Example:

Boy.txt

Good boy.

Good

boy.

0100 0111

0110 1111

0110 1111

0110 0100

0010 0000

0110 0010

0110 1111

0111 1001

0010 1110

on off

4

6

6

3

1

3

6

5

4

4

2

2

5

7

5

2

3

4

38 34

Page 65: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Exercise: On-Off Bits Counting

Example:

Boy.txt

Good boy.

Good

boy.

0100 0111

0110 1111

0110 1111

0110 0100

0010 0000

0110 0010

0110 1111

0111 1001

0010 1110

on off

4

6

6

3

1

3

6

5

4

4

2

2

5

7

5

2

3

4

38 34

There are 38 on-bits and 34 off-bits in file Boy.txt.

Page 66: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Exercise: On-Off Bits Counting

01101110mask 10000000&

mask

00000000

01101110

01000000&

01000000

01101110

00100000&

00100000

01101110

00010000&

00000000

01101110

00001000&

00001000

01101110

00000100&

00000100

01101110

00000010&

00000010

01101110

00000001&

00000000

On

Off

On

Off

Page 67: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Exercise: On-Off Bits Counting

int bitson(char c)

returns number of on-bit in c

int bitsoff(char c)

returns number of off-bit in c

Page 68: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Bit Fields

Page 69: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Why Bit Fields?

struct Card { unsigned face; unsigned suit; unsigned color;};

struct Card { unsigned face; unsigned suit; unsigned color;};

sizeof(struct Card) = ?

Page 70: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Bit Fields When storage space is at a premium, it may

be necessary to pack several objects into a single machine storage unit.

face

suit

color

Page 71: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Defining Bit Fields

face

suit

color

struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color: 1;};

struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color: 1;};

sizeof(struct BitCard) = ?

Page 72: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Defining Bit Fields

face

suit

color

struct BitCard { unsigned char face : 4; unsigned char suit : 2; unsigned char color: 1;};

struct BitCard { unsigned char face : 4; unsigned char suit : 2; unsigned char color: 1;};

sizeof(struct BitCard) = ?

Page 73: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Defining Bit Fields

Follow unsigned or signed integer (e.g.,

int, short, or char) member with a

colon (:) and an integer constant

representing the width of the field.

struct BitCard { unsigned char face : 4; unsigned char suit : 2; unsigned char color: 1;};

struct BitCard { unsigned char face : 4; unsigned char suit : 2; unsigned char color: 1;};

struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color: 1;};

struct BitCard { unsigned face : 4; unsigned suit : 2; unsigned color: 1;};

Page 74: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

Page 75: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example#include <stdio.h>#include "Cards.h"void fillDeck( Card * const wDeck ){ int i; /* counter */

for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; }}

void deal( const Card * const wDeck ){ int k1; /* subscripts 0-25 */ int k2; /* subscripts 26-51 */

for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { printf( "Face:%3d Suit:%2d Color:%2d ", wDeck[ k1 ].face, wDeck[ k1 ].suit, wDeck[ k1 ].color ); printf( "Face:%3d Suit:%2d Color:%2d\n", wDeck[ k2 ].face, wDeck[ k2 ].suit, wDeck[ k2 ].color ); }}

#include <stdio.h>#include "Cards.h"void fillDeck( Card * const wDeck ){ int i; /* counter */

for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; }}

void deal( const Card * const wDeck ){ int k1; /* subscripts 0-25 */ int k2; /* subscripts 26-51 */

for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { printf( "Face:%3d Suit:%2d Color:%2d ", wDeck[ k1 ].face, wDeck[ k1 ].suit, wDeck[ k1 ].color ); printf( "Face:%3d Suit:%2d Color:%2d\n", wDeck[ k2 ].face, wDeck[ k2 ].suit, wDeck[ k2 ].color ); }}

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

Page 76: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example#include <stdio.h>#include "Cards.h"void fillDeck( Card * const wDeck ){ int i; /* counter */

for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; }}

void deal( const Card * const wDeck ){ int k1; /* subscripts 0-25 */ int k2; /* subscripts 26-51 */

for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { printf( "Card:%3d Suit:%2d Color:%2d ", wDeck[ k1 ].face, wDeck[ k1 ].suit, wDeck[ k1 ].color ); printf( "Card:%3d Suit:%2d Color:%2d\n", wDeck[ k2 ].face, wDeck[ k2 ].suit, wDeck[ k2 ].color ); }}

#include <stdio.h>#include "Cards.h"void fillDeck( Card * const wDeck ){ int i; /* counter */

for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; }}

void deal( const Card * const wDeck ){ int k1; /* subscripts 0-25 */ int k2; /* subscripts 26-51 */

for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { printf( "Card:%3d Suit:%2d Color:%2d ", wDeck[ k1 ].face, wDeck[ k1 ].suit, wDeck[ k1 ].color ); printf( "Card:%3d Suit:%2d Color:%2d\n", wDeck[ k2 ].face, wDeck[ k2 ].suit, wDeck[ k2 ].color ); }}

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

// main.c#include <stdio.h>#include "Cards.h"

int main( void ){ Card deck[ 52 ]; // create array of Cards

fillDeck( deck ); deal( deck );}

// main.c#include <stdio.h>#include "Cards.h"

int main( void ){ Card deck[ 52 ]; // create array of Cards

fillDeck( deck ); deal( deck );}

Page 77: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

#include <stdio.h>#include "Cards.h"void fillDeck( Card * const wDeck ){ int i; /* counter */

for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; }}

void deal( const Card * const wDeck ){ int k1; /* subscripts 0-25 */ int k2; /* subscripts 26-51 */

for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { printf( "Face:%3d Suit:%2d Color:%2d ", wDeck[ k1 ].face, wDeck[ k1 ].suit, wDeck[ k1 ].color ); printf( "Face:%3d Suit:%2d Color:%2d\n", wDeck[ k2 ].face, wDeck[ k2 ].suit, wDeck[ k2 ].color ); }}

#include <stdio.h>#include "Cards.h"void fillDeck( Card * const wDeck ){ int i; /* counter */

for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = i % 13; wDeck[ i ].suit = i / 13; wDeck[ i ].color = i / 26; }}

void deal( const Card * const wDeck ){ int k1; /* subscripts 0-25 */ int k2; /* subscripts 26-51 */

for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { printf( "Face:%3d Suit:%2d Color:%2d ", wDeck[ k1 ].face, wDeck[ k1 ].suit, wDeck[ k1 ].color ); printf( "Face:%3d Suit:%2d Color:%2d\n", wDeck[ k2 ].face, wDeck[ k2 ].suit, wDeck[ k2 ].color ); }}

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

// Cards.h

// bitCard structure definition with bit fieldsstruct bitCard { unsigned face : 4; // 4 bits; 0-15 unsigned suit : 2; // 2 bits; 0-3 unsigned color : 1; // 1 bit; 0-1 }; // end struct bitCard

typedef struct bitCard Card; // new type name for struct bitCard

void fillDeck( Card * const wDeck ); // prototypevoid deal( const Card * const wDeck ); // prototype

// main.c#include <stdio.h>#include "Cards.h“

int main( void ){ Card deck[ 52 ]; // create array of Cards

fillDeck( deck ); deal( deck );}

// main.c#include <stdio.h>#include "Cards.h“

int main( void ){ Card deck[ 52 ]; // create array of Cards

fillDeck( deck ); deal( deck );}

Page 78: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

More on Defining Bit Fields

Unnamed bit field– Field used as padding in the structure– Nothing may be stored in the bits

– Unnamed bit field with zero width aligns next bit field to a new storage unit boundary

struct UnNameExample { unsigned a : 13; unsigned : 3; // unnamed unsigned b : 4;};

struct UnNameExample { unsigned a : 13; unsigned : 3; // unnamed unsigned b : 4;};

Page 79: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Example

struct UnnameExample { /* field 4 bits wide */ unsigned field1 :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 field2 :1;

/* align next field on a storage unit */ unsigned :0; unsigned field3 :6;};

struct UnnameExample { /* field 4 bits wide */ unsigned field1 :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 field2 :1;

/* align next field on a storage unit */ unsigned :0; unsigned field3 :6;};

Page 80: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

C Program Design

C Structures, Unions, Bit Manipulations and Enumerations

Enumeration Constants

Page 81: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Enumeration

enum Suits {CLUB, DIMOND, SPADE, HEART};

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

enum Suits {CLUB, DIMOND, SPADE, HEART};

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

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 =

Page 82: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

Enumeration

enum Suits {CLUB, DIMOND, SPADE, HEART};

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

enum Suits {CLUB, DIMOND, SPADE, HEART};

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

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 =

enum Suits {CLUB, DIMOND, SPADE, HEART};

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

enum Suits {CLUB, DIMOND, SPADE, HEART};

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

Page 83: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

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 *monthName[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

for ( month = JAN; month <= DEC; month++ ) printf( "%2d%11s\n", month, monthName[ month ] );}

#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 *monthName[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

for ( month = JAN; month <= DEC; month++ ) printf( "%2d%11s\n", month, monthName[ month ] );}

Page 84: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

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 *monthName[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

for ( month = JAN; month <= DEC; month++ ) printf( "%2d%11s\n", month, monthName[ month ] );}

#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 *monthName[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

for ( month = JAN; month <= DEC; month++ ) printf( "%2d%11s\n", month, monthName[ month ] );}

Page 85: C Program Design C Structures, Unions, Bit Manipulations and Enumerations

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("%d\n", action + 2); // operationAction--; // operation

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("%d\n", action + 2); // operationAction--; // operation