tags:

views:

298

answers:

2

Why does the following code compile?

#include <stdio.h>

int main(void) {
    getchar;
}
+13  A: 

The same reason 1; would compile, getchar is just an address to a function. The result is evaluated, then discarded. In the language specification, it's called an "expression statement";

eduffy
+24  A: 

Because function names are aliases to function pointers to those functions, which are themselves values much like integers.. This is semantically very similar to

#include <stdio.h>

int main(void) {
    42;
}

It is valid but pointless.

Alex Brown
And very annoying!!!! typing, "int x = getX" instead of "x = getX()" will work quite happily and put some random address value into x.
Martin Beckett
I hate C. >_< [15 char filler]
missingfaktor
@Rahul: That's not a very *polyglot* like attitude!
Tarydon
@Tarydon - is the word polyglot correct when dealing with typed (not spoken) languages?
jball
@jball : http://blogs.computerworld.com/15032/polyglot_programming_development_in_multiple_languages
missingfaktor
@Martin Beckett:Any decent compiler will issue a warning for such an assignment. If yours doesn't, get a better one (or quit disabling all the warnings -- especially in C, you should usually enable all warnings, and treat them as errors.
Jerry Coffin
@Rahul - Polyglot it is! I've always associated polyglot with spoken and multilingual with written (and therefore code), but it appears that I was putting meanings into the words that wasnt' there.
jball