A great use of a union is dealing with arrays as named values and also as indexed arrays: union { struct { int monHrs, tueHrs, wedHrs, thuHrs, friHrs; } wk; int hrs[5]; } data; Code can then clearly refer to the specific "data.wk.thuHrs", for example, OR it can, for instance, sum all values: for( int i = 0; i < sizeof(data)/sizeof(int); i++) total += data.hrs[ i ]; Of course, #define'd index names (or enum tokens) would work the same, but one gets tired of seeing "v[ INDEXNAME ] = 12;" vs "u.v.realname = 12"...
@grimvian Жыл бұрын
Very rare and fantastic video explaining from documentation. I really hope he would make videos about advanced C... At 9.52 Almost the way I use a union to change RBG colors for my C training.
@abhishekgupta-du1ly Жыл бұрын
It very really helpful for me 😊
@David-gu8hv4 жыл бұрын
You have to watch out for the size of Structs. If you have a struct with one char and one int on a 32-bit system the struct will be 8 bytes since the smallest amount of memory on 32-bits is 4 bytes. The char will claim 4 bytes even though it only uses 1.
@nguaial84908 жыл бұрын
Thanks very much. This clarified a lot. I am assuming that the size of int and size of float are the same in this UNION example.