E
E
Egor Lavrentiev2013-12-16 03:56:38
Programming
Egor Lavrentiev, 2013-12-16 03:56:38

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

1 answer(s)
S
Stanislav Skobelkin, 2013-12-16
@YaguarVL

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 intcan 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 cleast significant byte of the number is placed in, i.e. it is equivalent to x % 256.
If big-endian, then the clargest 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 1will return 1, for big-endian - 0.
The double question mark was used in C (where there is no type bool) for value normalization ( !!xequivalent 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( !!xis equivalent to (bool)x).
In any case, the point of the last expression is to return true/ 1if 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 question

Ask a Question

731 491 924 answers to any question