fundamental of programming (c) group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... ·...

38
Lecturer: Vahid Khodabakhshi Sharif University of Technology Department of Computer Engineering 1/38 Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Group 4 Lecture 10 Structures, Unions, Bit Manipulations and Enumerations CE 40153 - Fall 98

Upload: others

Post on 21-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Lecturer: Vahid Khodabakhshi

Sharif University of TechnologyDepartment of Computer Engineering 1/38

Bo

rro

wed

fro

m le

ctu

rer

no

tes

by

Om

id J

afar

inez

had

Fundamental of Programming (C) Group 4

Lecture 10

Structures, Unions, Bit Manipulations and Enumerations

CE 40153 - Fall 98

Page 2: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 2

Outline• Structures

– Be able to use compound data structures in programs

• Unions– Be able to share storage space of their members

• Bit fields Structures– Be able to do simple bit-vector manipulations

• Enumerations– Be able to use compound symbolic constants

Page 3: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 3

User Defined Data Types (typedef)• The C language provides a facility called typedef for creating

synonyms for previously defined data type names.• For example, the declaration:

typedef int Length;

makes the name Length a synonym (or alias) for the data type int.• The data type name Length can now be used in declarations in

exactly the same way that the data type int can be used:

Length a, b, len ;Length numbers[10] ;typedef char String[50];typedef int Array[10];String name;Array ages;

Page 4: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 4

Structures (struct) • Structures—sometimes referred to as aggregates—are collections

of related variables under one name

• Structures may contain variables of many different data types—incontrast to arrays that contain only elements of the same data type

• Structures are commonly used to define records to be stored infiles

• Pointers and structures facilitate the formation of more complexdata structures such as linked lists, queues, stacks and trees

• Structures are derived data types—they are constructed usingobjects of other types

Page 5: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 5

Declaring Structures (struct)• The name "employee" is called a structure tag

• Variables declared within the braces of the structuredefinition are the structure’s members

struct employee{

char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} Ali, Sara, empDTS[20];

struct employee Reza, *emp;

struct employee

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

};

struct employee Ali, emp[10];

struct

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} Ali;

Page 6: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 6

Declaring Structures (struct)• Often, typedef is used in combination with struct to declare a

synonym (or an alias) for a structure:

typedef struct

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} employee; /* The "alias"

employee Ali; /* Create a struct variable */

struct employee

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} Ali, Sara, empDTS[20];

struct employee Reza, *emp;

Page 7: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 7

Declaring Structures (struct)• Members of the same structure type must have

unique names, but two different structure types maycontain members of the same name without conflict

• Each structure definition must end with a semicolon

struct employee

{char Name[ 20 ];char Name[ 20 ]; // Error!!!int age;char gender;double hourlySalary;

} Ali, Sara, empDTS[20];

struct employee Reza, *emp;

struct Student

{char Name[ 20 ]; // OKint age;char gender;

};

struct Student Ce40153[80];

Page 8: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 8

Declaring Structures (struct)• A structure cannot contain an instance of itself• For example, a variable of type struct employee cannot be

declared in the definition for struct employee A pointer tostruct employee, however, may be included

• A structure containing a member that is a pointer to thesame structure type is referred to as a self-referentialstructure

struct employee2 {// …double hourlySalary; struct employee2 person; /* ERROR */struct employee2 *ePtr; /* pointer */

};

Page 9: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 9

Declaring Structures (struct)• The structure tag name is optional

• If a structure definition does not contain a structure tagname, variables of the structure type may be declaredonly in the structure definition—not in a separatedeclaration

struct

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} Ali;

Page 10: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 10

Structure’s sizeof• Structure definitions do not reserve any space in

memory; rather, each definition creates a new datatype that is used to define variables

sizeof(struct …) = sum of sizeof(members) + alignment padding(Processor- and compiler-specific)

struct employee{

char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

};

struct employee Ali, emp[10];printf("%d", sizeof(Ali));printf("%d", sizeof(emp));printf("%d", sizeof(struct employee));

Page 11: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 11

Memory layoutstruct COST {

int amount; char currency_type[2];

}struct PART {

char id[2];struct COST cost;int num_avail;

}

• Here, the system uses 4-byte alignment of integers, so amount and num_availmust be aligned Four bytes wasted for each structure!

id amount num_avail

cost

currency_type

Page 12: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 12

Memory layoutstruct COST {

int amount; char currency_type[2];

}struct PART {

struct COST cost;char id[2];int num_avail;

}

• Implementation dependent!!!

idamount num_avail

cost

currency_type

Page 13: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 13

Accessing Struct Members• Individual members of a struct variable may be

accessed using the structure member operator (thedot, "."):

myEmp.firstName ;employee. firstName; // Error

• Or , if a pointer to the struct has been declared andinitialized

employee *emp = &myEmp ;– by using the structure pointer operator :

emp -> firstName; // arrow operator– which could also be written as:

(* emp).firstName;

struct employee{

char firstName[ 20 ];// …

} myEmp;

Page 14: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 14

An Example - Initialization

struct identity js = {"Joe", "Smith", 25}, *ptr = &js ;

js.person.id = 123456789 ;js.person.gpa = 3.4 ;

printf ("%s %s %d %ld %f\n", js.FirstName, js.LastName, js.age, js.person.id, js.person.gpa) ;printf ("%s %s %d %ld %f\n", ptr->FirstName, ptr->LastName,ptr->age, ptr->person.id,

ptr->person.gpa) ;

struct identity{

char FirstName[30];char LastName[30];unsigned age;struct personal person;

};

//Create a struct but don’t reserve spacestruct personal{

long id; // student IDfloat gpa; // grade point average

};

js = {"Joe", "Smith", 25, 9, 10}js.personal.id Errorstrcpy(js.FirstName, "Joe");

Page 15: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 15

An Example - Assignment

struct identity js = {"Joe", "Smith", 25}, oj ;js.person.id = 123456789 ;js.person.gpa = 3.4 ;

oj = js;

printf ("%s %s %d %ld %f\n", oj.FirstName, oj.LastName, oj.age, js.person.id, oj.person.gpa) ;printf ("%s %s %d %ld %f\n", ptr->FirstName, ptr->LastName,ptr->age, ptr->person.id,

ptr->person.gpa) ;

struct identity{

char FirstName[30];char LastName[30];unsigned age;struct personal person;

};

//Create a struct but don’t reserve spacestruct personal{

long id; // student IDfloat gpa; // grade point average

};

Page 16: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 16

Arrays of Structures

personageLastNameFirstName

gpaid

20914015314Jafarinezhadomidstudents[0]

20222222290ShekarestaniSamadStudents[1]

2011111111100ShekarestaniKhaje Nezamstudents[2]

students[3]

struct identity{

char FirstName[30];char LastName[30];unsigned age;struct personal person;

} students[4];

//Create a struct but don’t reserve spacestruct personal{

long id; // student IDfloat gpa; // grade point average

};

struct identity sharifC40153[80] = {"omid", "Jafarinezhad", 14, 9140153, 20,"Samad", "Shekarestani", 90, 2222222, 20} ;

strcpy(sharifC40153[2].FirstName, "Khaje Nezam");strcpy(sharifC40153[2].LastName, "Shekarestani");sharifC40153[2]. age = 100;sharifC40153[2]. person.id = 11111111;sharifC40153[2]. person. gpa = 20;

Page 17: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 17

bool check_birthday(struct Date today, struct Date myFriend){

if ((today.month == myFriend.month) &&(today.day == myFriend.day))

return (true);return (false);

}int main(){

struct Friend friends[NFRIENDS]; struct Date today = {2012, 3, 11};// ...for (i = 0; i < NFRIENDS; i++) {

if(check_birthday(today, friends[i].Birthday))printf ("%s %s\n", friends[i].FirstName, oj.LastName) ;

} // …

An Example#define NFRIENDS 10struct Date{

unsigned year; unsigned month; unsigned day;

};struct Friend {

char FirstName[30];char LastName[30];struct Date Birthday;

};

typedef struct{

unsigned year; unsigned month; unsigned day;

} Date;bool check_birthday(Date today, Date myFriend){

//…}

Page 18: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 18

Pointers to StructuresDate create_date1(int month,

int day,

int year)

{

Date d;

d.month = month;

d.day = day;

d.year = year;

return (d);

}

void create_date2(Date *d,

int month,

int day,

int year)

{

d->month = month;

d->day = day;

d->year = year;

}

Copies date

Pass-by-reference

Date today;

today = create_date1(9, 4, 2008);

create_date2(&today, 9, 4, 2008);

Page 19: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 19

Pointers to Structuresvoid create_date2(Date *d,

int month,

int day,

int year)

{

d->month = month;

d->day = day;

d->year = year;

}

void foo(void)

{

Date today;

create_date2(&today, 9, 4, 2008);

} today.month:

today.day:

today.year:

0x1000

0x1004

0x1008

month: 9

day: 4

year: 2008

0x30A0

0x30A4

0x30A8

d: 0x10000x3098

9

4

2008

Page 20: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 20

Pointers to Structures

Date * create_date3(int month,

int day,

int year)

{

Date *d;

d->month = month;

d->day = day;

d->year = year;

return (d);

}

What is d pointing to?!?!

Page 21: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 21

Pointers to Structures

void changeByValue(Date date){

date.day ++;}void changeByRef(Date *date){

date->day++;}void printDate(const Date date){

printf("today(d/m/y) is : \n");printf("%d/%d/%d\n", date.day, date.month, date.year);

}

Date today = {2012, 3, 11};printDate(today);changeByValue(today);printDate(today);changeByRef(&today);printDate(today);

today(d/m/y) is :11/3/2012today(d/m/y) is :11/3/2012today(d/m/y) is :12/3/2012

Page 22: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 22

Compression of Structures• Structures may not be compared using

operators == and !=, because structuremembers are not necessarily stored inconsecutive bytes of memory

struct a {int a; // OKint b;

};struct a b, c;b.a = 10;b.b = 30;c = b;if(c == b) // Error

Page 23: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 23

Enumeration• Enumeration is a user-defined data type. It is defined using the

keyword enum and the syntax is:

enum tag_name {name_0, …, name_n} ;

• The tag_name is not used directly. The names in the braces aresymbolic constants that take on integer values from zero through n.As an example, the statement:

enum colors { red, yellow, green } ;

– creates three constants. red is assigned the value 0, yellow is assigned 1 andgreen is assigned 2

Page 24: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 24

Enumeration• Values in an enum start with 0, unless specified otherwise, and are

incremented by 1

• The identifiers in an enumeration must be unique

• The value of each enumeration constant of an enumeration can be setexplicitly in the definition by assigning a value to the identifier

• Multiple members of an enumeration can have the same constant value

• Assigning a value to an enumeration constant after it has been defined isa syntax error

• Use only uppercase letters enumeration constant names. This makes theseconstants stand out in a program and reminds you that enumerationconstants are not variables

Page 25: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 25

An Example/* This program uses enumerated data types to access the elements of an array */#include <stdio.h>int main( ){

int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12},{13,14,15,16,17,18,19},{20,21,22,23,24,25,26},{27,28,29,30,31,0,0}};

enum days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

enum week {week_one, week_two, week_three, week_four, week_five};

printf ("Monday the third week of March is March %d\n",March [week_three] [Monday] );

}

Page 26: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 26

An Example

/* enumeration constants represent months of the year */ enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

enum months month;

/* initialize array of pointers */const char *monthName[] = { "", "January", "February", "March",

"April", "May", "June", "July", "August", "September", "October",

/* loop through months */for (month = JAN; month <= DEC; month++ ) {

printf( "%2d%11s\n", month, monthName[month] );}

Page 27: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 27

Unions• A union is a derived data type—like a structure—with members

that share the same storage space

• For different situations in a program, some variables may not berelevant, but other variables are—so a union shares the spaceinstead of wasting storage on variables that are not being used

• The members of a union can be of any data type

• The number of bytes used to store a union must be at least enoughto hold the largest member

• Only one member, and thus one data type, can be referenced at atime

Page 28: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 28

Unions representation

union myDataUnion {

int i;

char c;

float f;

} u1, u2;

union myDataUnion u3;

u1.i = 4;

u1.c = ’a’;

u2.i = 0xDEADBEEF;

c

i

f

Page 29: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 29

Unions• The operations that can be performed on a union

are the following:– assigning a union to another union of the same type

– taking the address (&) of a union variable

– accessing union members using the structure memberoperator and the structure pointer operator

• Unions may not be compared using operators ==and != for the same reasons that structurescannot be compared

Page 30: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 30

Unions• In a declaration, a union may be initialized

with a value of the same type as the firstunion member

union a {

int a; // OKchar b[4];

};

union a b = {10};printf("%d", b.a);

Page 31: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 31

Unions• A union value doesn’t "know" which case it contains

union AnElt {

int i;

char c;

} elt1, elt2;

elt1.i = 4;

elt2.c = ’a’;

elt2.i = 0xDEADBEEF;

if (elt1 currently has a char) …

How should your program keep track whether elt1, elt2 hold an int or a char?

Basic answer: Another variable holds that info

Page 32: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 32

enum Union_Tag {IS_INT, IS_CHAR};

struct TaggedUnion {

enum Union_Tag tag;

union {

int i;

char c;

} data;

};

Tagged Unions• Tag every value with its case

Enum must be external to struct,

so constants are globally visible

Struct field must be named

Page 33: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 33

Bit-field Structures• C enables you to specify the number of bits in which an unsigned

or int member of a structure or union is stored

• This is referred to as a bit field

• Bit fields enable better memory utilization by storing data in theminimum number of bits required

• Bit field members must be declared as int or unsigned

• A bit field is declared by following an unsigned or int membername with a colon (:) and an integer constant representing thewidth of the field (i.e., the number of bits in which the member isstored)

Page 34: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 34

…8 bit ……8 bit ……8 bit …

Bit-field Structures• Notice that bit field members of structures are

accessed exactly as any other structure member

• Padded to be an integral number of words– Placement is compiler-specific

struct Flags

{

int f1:3;

unsigned int f2:1;

unsigned int f3:2;

} foo;

foo.f1 = -2;

foo.f2 = 1;

foo.f3 = 2;

1 1 0 1 1 0 … …

f1 f2 f3

Page 35: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 35

Unnamed Bit-fieldstruct example {

unsigned a : 13;

unsigned : 19;unsigned b : 4;

};

• uses an unnamed 19-bit field as padding—nothing can be stored in those 19 bits

• An unnamed bit field with a zero width is used to align the next bit field on a new storage-unit boundary

• For example, the structure definitionstruct example {

unsigned a : 13;

unsigned : 0;unsigned b : 4;

};

uses an unnamed 0-bit field to skip the remaining bits (as many as there are) of the storage unit in which a is stored and to align b on the next storage-unit boundary

Page 36: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 36

An Example - disk drive controller

• Frequently device controllers (e.g. disk drives)and the operating system need tocommunicate at a low level. Device controllerscontain several registers which may be packedtogether in one integer

Page 37: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 37

An Example - disk drive controllerstruct DISK_REGISTER {

unsigned ready:1;unsigned error_occured:1;unsigned disk_spinning:1;unsigned write_protect:1;unsigned head_loaded:1;unsigned error_code:8;unsigned track:9;unsigned sector:5;unsigned command:5;

};struct DISK_REGISTER *disk_reg = (struct DISK_REGISTER *) DISK_REGISTER_MEMORY;/* Define sector and track to start read */disk_reg->sector = new_sector;disk_reg->track = new_track;disk_reg->command = READ;/* wait until operation done, ready will be true */while ( ! disk_reg->ready ) ;/* check for errors */if (disk_reg->error_occured)

{ /* interrogate disk_reg->error_code for error type */switch (disk_reg->error_code)......

}

Page 38: Fundamental of Programming (C) Group 4ce.sharif.edu/courses/98-99/1/ce153-4/resources/root/... · 2019. 10. 14. · Lecturer: Vahid Khodabakhshi y Department of Computer Engineering

Structures, Unions, Bit Manipulations and Enumerations – Lecture 10

Sharif University of TechnologyDepartment of Computer Engineering 38

Notes of caution• Bit-field manipulations are machine dependent

• Attempting to access individual bits of a bit field as if they wereelements of an array is a syntax error. Bit fields are not "arrays ofbits"

• Attempting to take the address of a bit field (the & operator maynot be used with bit fields because they do not have addresses)

• Although bit fields save space, using them can cause the compilerto generate slower-executing machine-language code. This occursbecause it takes extra machine language operations to access onlyportions of an addressable storage unit. This is one of manyexamples of the kinds of space–time trade-offs that occur incomputer science