Example for declaring and assigning unions in c:
What is the output of below C program?
s.degree = 100;
printf("%d ", s.result);
s.result = 200;
printf("%d ", s.degree);
it prints 100 200
it prints garbage and 100.
it prints 100 and garbage
output is unpredictable, it may crash also.
In union only one memory space will be allocated that is big enough to accommodate any of those fields at a given point of time. so here union size is 4 bytes. whether we enter value for degree or result, it doesn't matter, when we read any element value, it always returns latest value written into that memory. so it prints 100 and 200.
Back To Top