Union u{  struct st {       int i : 4;       int j : 4;       int k : 4;       int l; }st; int i;}u;main(){    u.i = 100;    printf("%d, %d, %d",u.i, u.st.i, u.st.l);}

A) 40, 4, 0
B) 100, 4, 0
C) 0, 0, 0
D) 4, 4, 0

Showing Answers 1 - 7 of 7 Answers

sreelu

  • Mar 15th, 2006
 

ans is B)100,4,0because in structures&unions varible initilization is not possible.but bit by bit is possible.here :isbitwise operator.

shvr

  • Apr 8th, 2006
 

yap, the answer is B e.g. 100,4,0Here in struct and union variable we can not initialize the variables, so whatever output we get totally depend on statement in main function ( u.i = 100). In definition " int i: 4; " means the number of bits that integer variable will have means we have 4 bit varialbles ( st.i, st.j, st.k ). So when we initialze u.i in main function u.st.i j and k get som values.

  Was this answer useful?  Yes

paulson paul chambakottukudyil

  • Apr 18th, 2006
 

I didn't get any of the given answer. What I got is 4,6 and 0. I am using MS Visual studio compiler.

  Was this answer useful?  Yes

dasam

  • Mar 30th, 2007
 

In Unions, only the very first element can be initialised, rest cannot be. In the given code snippet, st - the object to the struct st is the first element of the union which is not initialised.

So,

u.i though it is initialised to 100 .. it prints 0 .. and st.xxx also prints 0 or garbage value.

so according to me, the answer is (0,0,0) or (0,garbage value, garbage value)

Correct me if iam wrong.

comments and suggestions are appreciated.

  Was this answer useful?  Yes

yba

  • Jul 10th, 2007
 

The output should contain 100 as the first number.

The union declares that st.i is a 4-bit field, and 100 can fit in 4 bits, however, you need to know how your compiler allocates bitfields.  Are they left to right or right to left?  Is the structure packed or padded?  Is your hardware big-endian or little-endian?  What is the size of an int?  The results will vary from platform to platform.

  Was this answer useful?  Yes

opal_sybil

  • Aug 28th, 2010
 

The struct notation
int i : 4;
specifies the size of integer i in bits, so the value of i will be represented
by 4 bits. In this case we have a signed int with a possible values of -8 to 7.


When first initializing the union member to 100, we get the following value
of the union:


100 or in a binary form: 01100100


Accessing u.st.i will produce 0100 in binary which is decimal 4.
Accessing u.st.j will produce 0110 in binary which is decimal 6.
Accessing u.st.l will produce 0000 in binary, since the union is treated as a
static variable and initialized statically to 0 by the compiler.


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions