CSE109 Week9
CSE109 Week9
Lecture: 20
Reference Book: Teach yourself C (3rd Ed.)
Chapter/Section: 10.4
struct b_type {
unsigned department: 3; /* up to 7 departments */
unsigned instock: 1; /* 1 if in stock, 0 if out */
unsigned backordered: 1; /* 1 if backordered, 0 if not */
unsigned lead_time: 3; /* order lead time in months */
} inv[MAX_ITEM];
In this case one byte can be used to store information on an inventory item that
would normally have taken 4 bytes without use of bit-fields.
inv[9].department = 3;
Bit-Fields
● It is not necessary to completely define all bits within a byte
or word. For example, this is perfectly valid:
struct b_type {
int a: 2;
int b: 3;
};
struct b_type {
char name[40]; /* name of item */
unsigned department: 3; /* up to 7 departments */
unsigned instock: 1; /* 1 if in stock, 0 if out */
unsigned backordered: 1; /* 1 if backordered, 0 if not */
unsigned lead_time: 3; /* order lead time in months */
} inv[MAX_ITEM];
● Because the smallest addressable unit of memory is a byte, you cannot obtain
the address of a bit-field variable.
Bit-Fields
● It is not necessary to name every bit when using bit-fields.
struct b_type {
unsigned first: 1;
int: 6;
unsigned last: 1;
};
● Because the smallest addressable unit of memory is a byte, you cannot obtain
the address of a bit-field variable.
Unions
● In C, a union is a single piece of memory that is shared by two or more
variables.
● The variables that share the memory may be different types. However, only one
variable may be in use at any one time.
● A union is defined much like a structure. Its general form is
union tag-name {
type member1;
type member2;
type member3;
.
.
type memberN;
} variable-names;
● Either the tag-name or the variable-names may be missing.
● Members may be any valid data type.
Unions
union u_type {
int i;
char c[2];
double d;
} sample;
d
c[0] + c[1]
i
Example
union intParts {
int theInt;
char bytes[sizeof(int)];
};
int main() {
union intParts parts;
parts.theInt = 5968145; // arbitrary number > 255 (1 byte)
int main() {
enum computer comp;
comp = CPU;
printf("%d", comp);
return 0;
}
Example
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main() {
printf("Press a key to select transport:\n");
printf("1. car\n2. train\n3. airplane\n4. bus\n");
tp = getch() - '0' - 1;
switch(tp) {
case car: printf("car"); break;
case train: printf("train"); break;
case airplane: printf("airplane"); break;
case bus: printf("bus");
}
}
Example
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main() {
printf("Press a key to select transport:\n");
printf("1. car\n2. train\n3. airplane\n4. bus\n");
tp = getch() - '0' - 1;
if (0 <= tp && tp < 4) printf("%s", transport_names[tp]);
}
Example
● The names of enumerated constants are known only to the
program, not any library functions.