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
}
The reversing of a string is nothing but simply substituting the last element of a string to the 1st position of the string. Different Methods to Reverse a String in C++ are: Making our own reverse function. Using 'inbuilt' reverse function.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With