>why would i as a c programmer use union instead of struct ?
if you want to have a structure that could potentially be many different things but can only be one thing at a time, they are commonly used for a variant in a structure.
>how is union declared right and how are fields of an union accesed correctly?
a union is declared the same way a struct is, only with the struct keyword replaced by union.
using a union will save you space, adn will also let you do fun stuff at a very low level.
here is an example
Code:
#include <stdio.h>
typedef union int32_bytes
{
int int_value;
struct { unsigned char b0, b1, b2, b3; } byte_value;
} INT32_VALUE;
int main()
{
INT32_VALUE v;
v.int_value = 123456789;
printf("Int value: %d\n", v.int_value);
printf("Bytes are: B0: %d, B1: %d, B2: %d, B3: %d\n",
v.byte_value.b0, v.byte_value.b1, v.byte_value.b2, v.byte_value.b3);
return 0;
}