Forum

> > Off Topic > C puzzle
Forums overviewOff Topic overviewLog in to reply

English C puzzle

2 replies
To the start Previous 1 Next To the start

old C puzzle

Lee
Moderator Off Offline

Quote
The following C code is valid (with accordance to C99, so gcc works, pretty sure vc++ may throw a hissy fit though) and prints something meaningful. What does it print and why?

1
int _[] = {1819043144, 1867980911, 6581362, 539780133}, __[] =  {1214606444, 1864390511, 1919706112, 744760576}, ___[] = {0xd>>0x2>0b10>>0b1};printf("%s",(char*)*((char*)&0[___])?_:__);

old Re: C puzzle

Flacko
User Off Offline

Quote
It prints "Hello World" because the integer data that you stored in the "_" and "__" arrays can be read as an array of characters in little-endian and big-endian machines respectively.

You only defined the 0-index for "___" and it's value should be 1 (3>1 = TRUE) since this value is an integer it takes 4 bytes of memory and is ordered accordingly to the processor endianness.

So the data should look like this on big endian machines:
00 00 00 01
Whereas in little endian machines it looks like this
01 00 00 00

Later, in printf's second parameter, you casted this value to a char* and then you dereferenced it to a simple char so only the first byte from the resulting integer would be read.

Or something like that I guess...

old Re: C puzzle

Lee
Moderator Off Offline

Quote
Very nice
_ contains the continguous memory for "Hello World" on little endian machines (all x86/64 intel) whereas __ contains the continguous memory on big endian machines.

0xd>>0x2>0b10>>0b1 evaluates to the integer 1, which consists for 4 bytes in the following configurations:

little endian: 1 0 0 0
big endian: 0 0 0 1

so by dereferencing
*((char*)&1)

we will get the highest byte (not the most significant, since that would defeat the whole purpose), which we push onto a ternary condition to test whether your computer uses little or big endian and outputs the correct result.

We then recast the int array into a pointer of atomic size of 1 byte (string basically) and run it through printf.
To the start Previous 1 Next To the start
Log in to replyOff Topic overviewForums overview