6

My expected output for u6.c was ABC but here I got CBA why is it so? Could you please shed some light on this with detailed explanation?

union mediatech
{ 
 int i; 
 char c[5]; 
};

int main(){
 mediatech u1 = {2};               // 1
 mediatech u2 = {'a'};             // 2
 mediatech u3 = {2.0};             // 3
 mediatech u6 = {'ABC'};           // 6

 cout<<"\nu6.i = "<<u6.i<<" u6.c="<<u6.c;  // o/p: u6.i=4276803  u6.c=CBA
}
timrau
  • 22,578
  • 4
  • 51
  • 64
uss
  • 1,271
  • 1
  • 13
  • 29

2 Answers2

14

You are using a multi-character literal 'ABC' to initialize an int.

How the multi-character literal (which is an uncommon way of using '') is interpreted is implementation-defined. Specifically, the order of the individual characters in the int interpretation is implementation-defined.

There is no portable (i.e. implementation-independent) way to predict what this program will do in terms of the order of the characters in 'ABC'.

From the Standard (C++11, §2.14.3/1):

[...] A multicharacter literal has type int and implementation-defined value.

jogojapan
  • 68,383
  • 11
  • 101
  • 131
5

http://en.wikipedia.org/wiki/Little_endian#Little-endian

You probably use processor with x86 architecture :), which is little-endian.

It means that when you assign character to char array they go to memory in same order, but when you read that memory as integer, it goes to processor register in reverse order.

Edited

Sorry, the same but in reverse order, you initialize integer with 'ABC' multi-character literal, which goes from processor register to memory in reverse order and as char array it becomes "CBA"