int main()
{
union {
struct {
char c[2];
char ch[2];
} s;
struct {
int i;
int j;
} st;
} u = { (12, 1), (15, 1) };
printf("%d %d ", u.st.i, u.st.j);
}
How come the above is printing “257 0”?
What difference is created by using {} instead of ()?
Both
(12, 1)and(15, 1)simplify to (oddly enough)1. This is because, as Omkant said, you’re using the comma operator, which executes each expression it divides, but returns the value of the final expression. The Wikipedia entry actually explains this pretty well.As a result,
u.s.c[0]gets filled with the first 1 andu.s.c[1]gets filled with the second 1. Since a union overlays intu.st.ioveru.c[2]andu.ch[2](assuming 8-bit chars and 32-bit ints), and the architecture is little-endian (known from your result), you have a 1 in the lowest byte ofu.st.iand a 1 in its second lowest byte, for a value of256*1 + 1 = 257.Meanwhile, no values were written to the memory of
u.st.j, so the 2nd output is 0.