23
int main(void)
{ 
    return('yes', *"no", **main, *********printf) ("hello world!\n") *0; 
}

outputs hello world!, but how does it actually work?

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
noob
  • 231
  • 1
  • 3
  • 2
    `return('yes', *"no", **main, *********printf) ("Its magical!\n") *0;` By the way, i compiled it and it actually works ._. – Warty Apr 19 '10 at 18:56
  • you have a strange style to write software!You will never receive a job at me. :-) – Oleg Apr 19 '10 at 18:59
  • C is really a perverted language :-) – Darin Dimitrov Apr 19 '10 at 19:07
  • 2
    As a pedantic remark, in ANSI C (in C89/90 as well) calling a variadic function (`printf` in this case) without declaring a prototype first is undefined behavior. So, from the pedantic point of view your program works only accidentally. You need to include `stdio.h` for it to become a defined C program. – AnT stands with Russia May 08 '10 at 20:18

2 Answers2

46

Two things really:

  1. Function pointers don't dereference the same as other pointers. *main == main
  2. A comma separated list returns the value of the last element in the list

So if we simplify the pointers:

int main(void)
{ 
    return('yes', *"no", main, printf) ("hello world!\n") *0; 
}

And using the last element in the list as the value of the list

int main(void)
{ 
    return printf("hello world!\n") *0; 
}

printf returns the number of characters printed

int main(void)
{ 
    return 13 *0; 
}

And 13*0 is left as an exercise to the reader.

rampion
  • 87,131
  • 49
  • 199
  • 315
12
('yes', *"no", **main, *********printf) 

will evaluate to *********printf, because comma operator evaluates its operands and returns value of last expression. *********printf is equal to printf, as dereferencing function pointer results in the same function pointer; it does nothing.

Next, result of first parenthesis, printf, is applied to ("hello world!\n") which results in text printed to screen. printf function returns number of characters written. That number is then multiplied with 0 and product is returned by main function.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275