views:

300

answers:

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

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

+35  A: 

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
Your gravatar icon is freaky, but nevertheless good answer
Anthony Forloney
Some friends of mine were having a mustache growing contest, and I had to shave. So I wore a fake mustache that day.
rampion
+1 for the exercise to the reader;)
el.pescado
to be pedantic: function pointers dereference just fine, but the resulting function designator will be immediately converted back to a function pointer
Christoph
@Christoph: +1 good to know
rampion
+11  A: 
('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.

el.pescado