Why is he printing the return line?

My expected result for u6.c was ABC, but here I got CBA, why is this so? Could you shed some light on this with a 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 } 
+6
source share
2 answers

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

You are probably using a processor with x86 architecture :) which is a little-endian.

This means that when you assign a character to a char array, they go into memory in the same order, but when you read this memory as a whole, it goes into the processor register in the reverse order.

Edited

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

+5
source

You use the multi-character literal 'ABC' to initialize an int .

How a multi-character literal is interpreted (which is an unusual way of using '' ) is determined by the implementation. In particular, the order of individual characters in an int interpretation is determined by the implementation.

There is no portable (i.e. implementation independent) way of predicting what this program will do in terms of character order in 'ABC' .

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

[...] A multichannel literal is of type int and has a value defined by the implementation.

+14
source

Source: https://habr.com/ru/post/947193/


All Articles