这编译没有任何警告。
这在 C 和 C++ 中是否合法,还是仅在 gcc 和 clang 中有效?
如果是合法的,是不是C99之后的新东西?
void f(){
}
void f2(){
return f();
}
更新
正如“Rad Lexus”所建议的那样,我尝试了这个:
$ gcc -Wall -Wpedantic -c x.c
x.c: In function ‘f2’:
x.c:7:9: warning: ISO C forbids ‘return’ with expression, in function returning void [-Wpedantic]
return f();
$ clang -Wall -Wpedantic -c x.c
x.c:7:2: warning: void function 'f2' should not return void expression [-Wpedantic]
return f();
^ ~~~~~
1 warning generated.
$ gcc -Wall -Wpedantic -c x.cc
(no errors)
$ clang -Wall -Wpedantic -c x.cc
(no errors)
更新
有人问这个建筑有什么帮助。好吧,或多或少是语法糖。这是一个很好的例子:
void error_report(const char *s){
printf("Error %s\n", s);
exit(0);
}
void process(){
if (step1() == 0)
return error_report("Step 1");
switch(step2()){
case 0: return error_report("Step 2 - No Memory");
case 1: return error_report("Step 2 - Internal Error");
}
printf("Processing Done!\n");
}
原文由 Nick 发布,翻译遵循 CC BY-SA 4.0 许可协议
C11 , 6.8.6.4 “
return
声明”:不,你不能使用表达式,即使它是
void
类型。来自同一文件的前言:
所以这是从 C89 -> C99(语言标准的第二版)的变化,从那以后一直如此。
C++14 , 6.6.3 “
return
声明”:是 的, 如果 表达式是 void 类型(自 C++98 以来一直有效),您可以使用表达式。