in C Plus Plus by

What is the difference between struct and union in C?

1 Answer

0 votes
by

A struct is a group of complex data structures stored in a block of memory where each member on the block gets a separate memory location to make them accessible at once

Whereas in the union, all the member variables are stored at the same location on the memory as a result to which while assigning a value to a member variable will change the value of all other members.

/* struct & union definations*/
struct bar {
	int a;	// we can use a & b both simultaneously
	char b;
}	bar;

union foo {
	int a;	// we can't use both a and b simultaneously
	char b;
}	foo;

/* using struc and union variables*/

struct bar y;
y.a = 3;	// OK to use
y.b = 'c'; // OK to use

union foo x;
x.a = 3; // OK
x.b = 'c'; // NOl this affects the value of x.a!
...