why does this program output 3,2,515?
Code:#include<stdio.h> int main() { union a { short int i; char ch[2]; }; union a u; u.ch[0]=3; u.ch[1]=2; printf("%d %d %d\n",u.ch[0],u.ch[1],u.i); return 0; }
This is a discussion on c program within the C Programming forums, part of the General Programming Boards category; why does this program output 3,2,515? Code: #include<stdio.h> int main() { union a { short int i; char ch[2]; }; ...
why does this program output 3,2,515?
Code:#include<stdio.h> int main() { union a { short int i; char ch[2]; }; union a u; u.ch[0]=3; u.ch[1]=2; printf("%d %d %d\n",u.ch[0],u.ch[1],u.i); return 0; }
because you posted in the C++ forum when this is clearly C code. did you really not see the C forum directly below this one? you should learn the difference between C and C++. it is fairly significant.
that being said, a short int is (usually) the same size as a char[2], but they represent totally different things in memory. what you really have is a short int sharing memory space with a char[2], and since your array contains 3 and 2, you get (2 * 256) + 3 = 515.
Last edited by Elkvis; 05-28-2012 at 08:43 AM.
Moved thread
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
Try hex output to help with illustrationCode:printf("%x %x %x %d \n", u.ch[0], u.ch[1], u.i, u.i ); /*output: 3 2 203 515 Your answer lies in how data is stored in bits. Here's an illustration of your two bytes with the 3 an 2 in them in binary. See how the bit values are combined to determine tha two byte (short) value: 2 3 0000 0010 0000 0011 <- bits with 1 are "set" or "on" 52 1631 8421 <- each set bit place is worth this much. (read vertically) 15 2426 26 8 512 <- add up the bit values. 2 1 --- 515 */
which part of this program is incompatible with C++? seems to compile fine on VC++ and G++ with all warnings enabled.this is clearly C code
"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook
You could always try
printf("Answer=%lu\n", (unsigned long)sizeof('a') );
Within a C program and a C++ program.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.