Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the C++ compiler complain when I use functions without parentheses?

I was looking at some code a friend sent me, and he said: "It compiles, but doesn't work". I saw that he used the functions without the parentheses, something like this:

void foo(){
  cout<< "Hello world\n";
}

int main(){
  foo; //function without parentheses
  return 0;
}

The first I said was "use parentheses, you have to". And then I tested that code - it does compile, but when executed doesn't work (no "Hello world" shown).

So, why does it compile (no warning at all from the compiler GCC 4.7), but doesn't work?

like image 419
samkpo Avatar asked Jun 18 '12 11:06

samkpo


1 Answers

It surely warns if you set the warning level high enough.

A function name evaluates to the address of the function, and is a legal expression. Usually it is saved in a function pointer,

void (*fptr)() = foo;

but that is not required.

like image 94
Bo Persson Avatar answered Sep 28 '22 02:09

Bo Persson