Okay, this is a difficult one to explain. I've tried it twice. I've failed twice. Here goes anyway! It all boils down to the fact that information is only bytes which we interpret to suit our needs. The hex number #60 (0x60 for us C freaks) can be interpreted in a number of ways: in 6502 machine language, it's interpreted as RTS. If you treat it as an ASCII character, it's the back-quote character (‘). As an integer, it's the number 96. Data is data. Data plus interpretation equals meaningful information 1.
Unions are a way of imposing different interpretations (‘views’) on the same block of memory. This is required quite often. For example, there are eight bytes on the Oric-1/Atmos' page 2, organised as four 16-bit ints. They are used for storing the arguments to various calls to graphics and sound functions. When calling the CURSET command, these contain the X and Y coordinates of the pixel we want to change; the third integer contains the action to be performed on the pixel. When calling the SOUND command, the same three integers contain the channel number, frequency and volume needed by the command. Got it so far? Right. I'll implement the same example:
enum CURSET_mode {reset=0, set=1, xor=2, none=3}; struct CURSET_data { unsigned short int x, y; enum CURSET_mode mode; }; struct SOUND_data { unsigned short int channel, freq, volume; }; union OS_call { struct CURSET_data CURSET; struct SOUND_data SOUND; }; union OS_call data;
We define various data structures, and a union of two of them. We also declare a variable data of type union OS_call. Say we want to call the Oric operating system to draw a pixel. We'll access 2 CURSET's view of the data by using the fields data.CURSET.x, data.CURSET.y, and data.CURSET.mode (note a typical use of enum there). To make a SOUND, we'll access data.SOUND.channel, data.SOUND.freq and data.SOUND.volume. The CURSET and SOUND parts of the union (and as many others as we wish to define) refer to the same block of memory, but allow you to interpret it in different ways. By the way, a union takes as much space as its biggest member.




Add new comment