Re: printing all variables in union



rahul8143@xxxxxxxxx writes:
> hello,
> what will be output of following program on INTEL machine
> #include <stdio.h>
>
> void main()
> {
> union s
> {
> int i;
> char ch[2];
> };
> union s obj;
> obj.i=256;
> printf("%d\n",obj.i,"%d",obj.ch[0],"%d",obj.ch[1]);
> }

Since you declared main as returning void, rather than the correct
return type of int, it invokes undefined behavior (unless you're using
an implementation that specifically accepts void main()). If you had
been following this newsgroup, or if you had read the FAQ, you would
know that.

Assuming your implementation accepts "void main()", the output on any
system will be the string "256" followed by a newline. If you had
actually tried running the program before posting it, you would know
that as well, though you might not yet understand why. Read your
textbook, or your system's documentation, to understand how the
printf() function works (hint: it takes a single format string).

I suspect you're also assuming that an int is two bytes. It may be,
but it commonly isn't.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • (long) An AES implementation for 32-bit platforms
    ... union BLOCK ... needed in the AES algorithm. ... typedef unsigned int word; ... void computetables() ...
    (sci.crypt)
  • Help in Java swings(internal Frame)
    ... public int getSize() ... public void valueChanged{ ... private JScrollPane scrollPane1; ... public class PeakContainer extends JInternalFrame ...
    (comp.lang.java.programmer)
  • [PATCH] get rid if __cpuinit and __cpuexit
    ... unsigned long action, void *hcpu) ... unsigned int cpu = hcpu; ... -static int __cpuinit ... __cpu_up(unsigned int cpu) ...
    (Linux-Kernel)
  • [PATCH,RFC 2.6.14 09/15] KGDB: SuperH-specific changes
    ... This adds basic support for KGDB on SuperH as well as adding some architecture ... -static int kgdb_uart_getchar ... -static void kgdb_uart_putchar ... * The command-line option can include a serial port specification ...
    (Linux-Kernel)
  • problem in java swings
    ... public int getSize() ... public void valueChanged{ ... private JScrollPane scrollPane1; ... public class PeakContainer extends JInternalFrame ...
    (comp.lang.java.programmer)