Reputation: 101
I'm trying to understand what happens in the comparison statement below.
int n = 1;
std::puts( ((char*)&n)[0] == 1 ? "-Y-" : "-N-" );
The statement above's output for me is -Y-
My first question is, why cast the pointer to a char*
instead of an int*
?
Also, if we are comparing a char to an int, it seems like the answer should be -N-
.
Does the char automatically get converted to an int when comparing to 1
?
Upvotes: 0
Views: 180
Reputation: 2298
You may be comparing a char to an int, but what is the value of the char here? You can't tell just from the code that you posted and it may be different in different environments.
You are not converting a char to an int and comparing, you are slicing off a part of an int, treating it as a char, then promoting it and comparing it. On a little-endian machine it will probably be a 1, on a big-endian machine a 0.
Upvotes: 1
Reputation: 55271
That is some horrible code, but the reason it outputs -Y-
is because you're effectively treating the contents of the int n
as a byte array, and the byte order of your machine is such that it's storing the value of int = 1
in same way as char[] = { 1 , 0 , 0, 0};
(don't rely on this!)
Hence this is like you were doing
int someInt = 1;
char someChar = 1;
if (someInt == someChar)
{
puts("-Y"-):
}
else
{
puts("-N"-):
}
To answer your second question (and the title question), yes C++ (and C) will implicitly do type promotion: see Implicit type conversion rules in C++ operators
Upvotes: 3
Reputation: 414275
The answer depends on endianess:
>>> struct.pack('<i', 1)
'\x01\x00\x00\x00'
>>> struct.pack('>i', 1)
'\x00\x00\x00\x01'
-Y-
corresponds to little-endian byte order.
Upvotes: 1