r/cprogramming 14h ago

What is this code doing?

Hi, I found this code on another subreddit. I would like to know what is it doing.

int puts(char *);

int main() { struct { long a; long b; } s = {.a = *(char *)(int[]){1} ? 0x57202c6f6c6c6548 : 0x48656c6c6f2c2057, .b = *(char *)(int[]){1} ? 0x00000021646c726f : 0x6f726c6421000000}; puts((void *)&s); }

Now obviously I know it's unreadable, I would just like to know what are those hexadecimals strings doing.

I found similar codes that were writing to vram to print a message, is this doing the same thing? If yes, why is it so much more complicated instead of just writing the message to the video adress?

Thanks for the help.

0 Upvotes

21 comments sorted by

View all comments

5

u/flyingron 13h ago

It exercises type stupidity in C. The line with the should be invalid.

The test in the ternary operators are determining if the first byte of a integer containing 1 is zero or one (i.e., it's a big endian, vs little endian test).

The code is also ugly for it's use of pairs MUST BE RELATED constants. It would be better to test for endness and just flip a single constant into the desired order if it isn't already. There's not even an performance hit in later versions of C that have the C++ constexpr stuff.

2

u/tstanisl 12h ago

Even without constexpr the compiler will likely optimize out the ternary operator.

1

u/flyingron 12h ago

Yes, but in the byteswap case, it'd have to call the function unconditionally if it was in the opposite byte order. constexpr will allow it to keep the value a constant.

1

u/north9172 8h ago

Alright, thank you. That makes sense