Why doesn't the C++ compiler complain when I u

2020-03-18 02:57发布

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?

3条回答
Animai°情兽
2楼-- · 2020-03-18 03:31

You need to increase the warning level that you use. foo; is a valid expression statement (the name of a function converts to a pointer to the 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
查看更多
唯我独甜
3楼-- · 2020-03-18 03:31
foo;

You're not actually 'using' the function here. You're just using the address of it. In this case, you're taking it but not really using it.

Addresses of functions (i.e. their names, without any parenthesis) are useful when you want to pass that function as a callback to some other function.

查看更多
孤傲高冷的网名
4楼-- · 2020-03-18 03:46

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.

查看更多
登录 后发表回答