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

你离开我真会死。 提交于 2019-12-01 04:14:16

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.

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
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!