7

我正在查看朋友发给我的一些代码,他说:“它可以编译,但不起作用”。我看到他使用了不带括号的函数,如下所示:

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

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

我说的第一个是“使用括号,你必须”。然后我测试了该代码 - 它确实编译,但执行时不起作用(没有显示“Hello world”)。

那么,为什么它可以编译(编译器GCC 4.7根本没有警告),但不起作用?

4

3 回答 3

12

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.

于 2012-06-18T11:59:40.737 回答
11

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
于 2012-06-18T12:00:30.367 回答
3
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.

于 2012-06-18T12:00:46.447 回答