c++ - confusion in union concept -


#include<stdio.h> union node { int i; char c[2]; }; main() { union node n; n.c[0] = 0; n.c[1] = 2; printf("%d\n", n.i); return 0; } 

i think gives 512 output becouse c[0] value stores in first byte , c[1] value stores in second byte, gives 1965097472. why ?. compiled program in codeblocks in windows.

your union allocates 4 bytes, starting off as:

[????] [????] [????] [????] 

you set least 2 significant bytes:

[????] [????] [0x02] [0x00] 

you print out 4 bytes integer. you're not going 512, necessarily, because can in significant 2 bytes. in case, had:

[0x75] [0x21] [0x02] [0x00] 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

c++ - Accessing inactive union member and undefined behavior? -

php - Get uncommon values from two or more arrays -