Answer the question
In order to leave comments, you need to log in
Difficult job interview
As one of the interview questions, I was presented with the following code:
bool XYZ()
{
unsigned int x = 1;
unsigned char c = *(unsigned char*)&x;
return !!c;
}
And a question for him: What does this code do and where can it be applied on a 32-bit architecture. (I don’t remember the question verbatim, but I sort of conveyed the essence correctly)
And at first glance and after a week of reflection, it seems that the function always returns true, but is it?
Answer the question
In order to leave comments, you need to log in
The question is a bit misleading. 32-bit does not play a big role here (it is only important that the architecture is not 8-bit, where the length of the type int
can be equal to the length of the type char
, but still this is also incorrect, because the sizes of types do not depend on the bitness of the architecture, it was necessary specify the bit width of the type int
), the byte order plays a role.
If little-endian (Intel order), then the c
least significant byte of the number is placed in, i.e. it is equivalent to x % 256
.
If big-endian, then the c
largest significant byte of the number is placed in, i.e. it is equivalent x >> 24
(for 32-bit architecture).
Accordingly, for little-endian this operation on a number 1
will return 1
, for big-endian - 0
.
The double question mark was used in C (where there is no type bool
) for value normalization ( !!x
equivalent x > 0 ? 1 : 0
).
In C++ , !
returns bool
, and the result of applying the negation twice is essentially a type conversion of the original value to bool
( !!x
is equivalent to (bool)x
).
In any case, the point of the last expression is to return true
/ 1
if the architecture is little-endian, otherwise it is false
/ 0
.
That is, this function could be IsLittleEndian()
called .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question