Thursday 13 September 2012

Usage Of Unions with typedef

Can you predict the output of this program ?
main()
{
        typedef union {
           int     a;
           char    b[10];
           float   c;
        } Union
        Union   x, y = { 100 }; // here y = 100 bcoz its property of union
        x.a = 50;s
trcpy (x.b, "hello");
        x.c = 21.50;
        printf ("Union x : %d %s %f\n", x.a, x.b, x.c);
        printf ("Union Y : %d %s %f\n", y.a, y.b, y.c);
}


Solution:

This is the  problem  about  Unions.  Unions are  similar to
structures  but it  differs  in  some  ways.  Unions  can be
assigned  only  with one  field at any time.  In this  case,
unions x and y can be  assigned  with any of the one field a
or b or c at one time.  During  initialisation  of unions it
takes  the value  (whatever  assigned  ) only for the  first
field.  So, The statement y = {100}  intialises  the union y
with field a = 100.
In this  example,  all fields of union x are  assigned  with
some  values.  But at any time only one of the  union  field
can  be  assigned.  So,  for  the  union  x the  field  c is
assigned as 21.50.
Thus, The output will be 
        Union x : 22 22 21.50
        Union Y : 100 22 22
        ( 22 refers unpredictable results ) 

Reference :


http://www.c-puzzles.thiyagaraaj.com/level-two.html


No comments:

Post a Comment

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...