简体   繁体   中英

Why it is printing reverse string?

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
}

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 (ie 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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM