The C programming language introduced a data structure called union which allowed that data structure to contain a range of different data types which could come and go in relevance, during program execution, for many and various purposes, as the programmer saw fit. Perhaps think of it like an artist’s palette or the HTML5 element canvas (or the canvas of Tcl/TK). Union can be used in C++ as well, as this tutorial intimates, as Xcode (on a Mac) is by default a C++ environment, which tolerates a C compilation if you code your code in the proper way. Today’s tutorial also uses some other concepts, one of which hopefully of interest, is the use of a bit field. In making this tutorial a topic of change between C++ and C came about to do with the use of enum and trying to work out the bit offset of a bit field within a bit field struct. Wanted to use a generic approach, and the closest is a macro called offsetof in stddef.h but found that various platforms and the issue of wanting the same codebase for C and C++ precluded its use … you might want to read more here.
Background reading for tutorial (all links by tutorialspoint … thanks):
Here is a tutorial that introduces you to some C programming code for the use of a union using Xcode, (at the end of tutorial is shown running in a Linux Mac OS X Terminal (application) bash environment) …
Let’s see some C via XCode for this …
Link to some downloadable code … rename to main.cpp (or main.c … see how XCode can do C as well!) for use.
Regarding C programming generally really like βUsing ANSI C in UNIXβ by Werner Feibel.
If this was interesting you may be interested in this too.
33 Responses to C Union Primer Tutorial