MYF

[RA] Ch38 Miscellaneous C and C++ Topics

Reading Assignment: All of Programming Ch38 Miscellaneous C and C++ Topics

Ternary If

1
a ? b : c

Unions

C and C++ both include the notion of a union–a type which contains multiple other types that overlap each other in memory. The declaration of a union looks very much like the declaration of a struct. The main difference is that where a struct places each element one after the other, a union places all of the elements “on top of” each other. Accordingly, the size of a union is the size of its largest member (whereas the size of a struct is the sum of the sizes of its members, plus possibly some extra space to align them properly). For example, we might write:

1
2
3
4
5
6
union nums{
uint64_t qword;
uint32_t dwords[2];
uint16_t words[4];
uint8_t bytes[8];
}

A variable of type nums will consist of one box which we can “look at” multiple ways by accessing its different fields. For example, we could write the following C code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>
union nums{
uint64_t qword;
uint32_t dwords[2];
uint16_t words[4];
uint8_t bytes[8];
};
int main(void){
union nums n;
n.qword=0x0123456789ABCDEF;
for(int i = 0; i < 2; i++) {
printf("n.dwords[%d] = 0x%X\n", i, n.dwords[i]);
}
for(int i = 0; i < 4; i++) {
printf("n.words[%d] = 0x%X\n", i, n.words[i]);
}
for(int i = 0; i < 8; i++) {
printf("n.bytes[%d] = 0x%X\n", i, n.bytes[i]);
}
return EXIT_SUCCESS;
}

The output of this program on my computer is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
n.dwords[0] = 0x89ABCDEF
n.dwords[1] = 0x1234567
n.words[0] = 0xCDEF
n.words[1] = 0x89AB
n.words[2] = 0x4567
n.words[3] = 0x123
n.bytes[0] = 0xEF
n.bytes[1] = 0xCD
n.bytes[2] = 0xAB
n.bytes[3] = 0x89
n.bytes[4] = 0x67
n.bytes[5] = 0x45
n.bytes[6] = 0x23
n.bytes[7] = 0x1

-w289