Rajeev Singh Rajeev Singh - 3 months ago 10
C Question

This obfuscated C code claims to run without a main(), but what does it really do?

#include <stdio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)

int begin()
{
printf("Ha HA see how it is?? ");
}


Does this indirectly call
main
? If yes, then how?

Answer

C define execution environment in two categories: freestanding and hosted. In both execution environment a function is called by the environment for program startup.
In a freestanding environment program startup function can be implementation defined while in hosted environment it should be main. No program in C can run without program startup function on the defined environments.

In your case, main is hidden by the preprocessor definitions. begin() will expand to decode(a,n,i,m,a,t,e) which further will be expanded to main.

int begin() -> int decode(a,n,i,m,a,t,e)() -> int m##a##i##n() -> int main() 

decode(s,t,u,m,p,e,d) is a parameterized macro with 7 parameters. Replacement list for this macro is m##s##u##t. m, s, u and t are 4th, 1st, 3rd and 2nd parameter used in the replacement list.

s, t, u, m, p, e, d
1  2  3  4  5  6  7

Rest are of no use (just to confuse). Argument passed to decode is "a,n,i,m,a,t,e" so, the identifiers m, s, u and t are replaced with arguments m, a, i and n, respectively.

 m --> m  
 s --> a 
 u --> i 
 t --> n