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

I looked at the code that a friend sent me and he said: "It compiles, but does not work." I saw that he used functions without parentheses, something like this:

void foo(){ cout<< "Hello world\n"; } int main(){ foo; //function without parentheses return 0; } 

The first thing I said was "use the parentheses you need." And then I tested this code - it compiles, but when it does not work ("Hello world" is not displayed).

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

+7
source share
3 answers

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

The name of the function evaluates the address of the function and is a legal expression. It is usually stored in a function pointer,

 void (*fptr)() = foo; 

but it is not required.

+12
source

You need to increase the warning level that you are using. foo; - a valid expression operator (the name of the function is converted to a pointer to a named function), but it has no effect.

I usually use -std=c++98 -Wall -Wextra -pedantic , which gives:

 <stdin>: In function 'void foo()': <stdin>:2: error: 'cout' was not declared in this scope <stdin>: In function 'int main()': <stdin>:6: warning: statement is a reference, not call, to function 'foo' <stdin>:6: warning: statement has no effect 
+11
source
 foo; 

You are not using the function here. You just use its address. In this case, you accept it, but do not use it.

Function addresses (i.e. their names without any parentheses) are useful when you want to pass this function as a callback to some other function.

+3
source

All Articles