[C++] Interesting example of C++ code obfuscation
Recently a friend of mine has given me a piece of code in C++:
puts(&3["abcdef"]); |
At first glance it seems to not compile at all. But not only it compiles, but also prints “def”.
It’s an interesting example of “syntatic sugar“. In C++ synax tab[i] is an human-readable alias to *(tab+i). So following code:
int tab[4]; tab[3] = 17; printf("%d %d %d\n", tab[3], 3[tab], *(tab+3)); |
prints “17” three times.
Let’s go back to our code.
3["abcdef"] |
means
*(3 +"abcdef") |
so this expression returns “d”. But when we obtain memory adress of “d” using & operator, we can print string that starts at “d” using puts command.
So the code prints “def”.
For more interesting examples of code obsfuscation visit: www.ioccc.org or International Obfuscated C Code Contest.