Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is printing reverse string?

Tags:

c++

unions

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
}
like image 726
sree Avatar asked Jun 13 '13 08:06

sree


People also ask

What is reversing a string?

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.


2 Answers

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.

like image 184
jogojapan Avatar answered Sep 18 '22 23:09

jogojapan


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"

like image 33
Davit Samvelyan Avatar answered Sep 17 '22 23:09

Davit Samvelyan