r/cprogramming • u/north9172 • Sep 13 '26
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.
21
u/mikeblas Sep 13 '26
Here's your code, more reasonably formatted:
4
u/FitMatch7966 Sep 14 '26
I believe it is an obfuscation example. It's treating longs as strings and then outputting it. If I decoded it right, it prints out "Hello World!" Now, it isn't the best example of obfuscation since the string "Hello World!" would still appear in the executable, at least the two part of it, "Hello W" and "orld!"
8
u/flyingron Sep 13 '26
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.
5
u/Classic-Rate-5104 Sep 13 '26
Not everything that's possible will also make sense. This program, i think, is (a) unreadable, (b) makes use of undefined behavior and (c) depends on the specific byte ordering of the underlying processor
3
u/zhivago Sep 13 '26
Implementation defined behavior mostly, except for the illegal redefinition of puts, which has undefined behavior.
But it's intended to output "Hello, World!".
It may even do so on some systems.
Or it might not.
Either way, it's neither portable nor good. :)
2
u/ACRM64 Sep 15 '26
Please be a bit less rude in future. Try to be constructive instead.
Whoever is correct, the standard needs to be updated to clarify these points. The wording is interpretable in multiple ways.
Assuming your interpretation is correct, why is it correct? What does it add to the standard? Where is it actually useful when we have seen that we can pass a pointer to an unqualified type into a function that expects a pointer to a qualified type? The purpose of the prototype is not changed whether the qualifier is there or not.
Rather than give examples of code that show a compilers error messages, find an example where this behaviour is helpful.
1
u/richardxday Sep 13 '26
Look at the hex numbers within the ternaries, what do you notice about them?
-4
u/agidu Sep 13 '26
It’s subtracting the array length