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 | union nums{ |
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 |
|
The output of this program on my computer is
1 | n.dwords[0] = 0x89ABCDEF |