返回无效的有效代码吗?
我发现以下代码被 Visual C++ 2008 和 GCC 4.3 编译器接受:
void foo()
{
}
void bar()
{
return foo();
}
我对它的编译感到有点惊讶。这是语言特性还是编译器中的错误? C/C++ 标准对此有何规定?
I found out that the following code gets accepted by Visual C++ 2008 and GCC 4.3 compilers:
void foo()
{
}
void bar()
{
return foo();
}
I am a bit surprised that it compiles. Is this a language feature or is it a bug in the compilers? What do the C/C++ standards say about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 C++ 的语言功能
C++ (ISO 14882:2003) 6.6.3/3
C (ISO 9899:1999) 6.8.6.4/1
It's a language feature of C++
C++ (ISO 14882:2003) 6.6.3/3
C (ISO 9899:1999) 6.8.6.4/1
是的,这是有效的代码。当您有模板函数时,这是必要的,以便您可以使用统一的代码。例如,
现在,当第二个参数是某种特定类型时,
g
可能会被重载以返回 void。如果“returning void”无效,则对f
的调用将会中断。Yes, it is valid code. This is necessary when you have template functions so that you can use uniform code. For example,
Now,
g
might be overloaded to return void when the second argument is some particular type. If "returning void" were invalid, the call tof
would then break.这是有效的,并且非常有用,例如,当您想在返回之前进行一些错误处理时,可以创建更清晰的代码:
This is valid and can be quite useful for example to create cleaner code in situations when you want to do some error handling before returning:
确实有效。我经常将它用于输入验证宏:
Valid indeed. I use it often for input validation macros: