【发布时间】:2016-06-29 11:43:42
【问题描述】:
编译时没有任何警告。
这在 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");
}
【问题讨论】:
-
投票重新开放;建议的副本仅适用于 C++。这也被标记为 C。(C 和 C++ 在使用
void方面有很大不同)。 -
所以你要的是 C 还是 C++?选择一种语言。
-
注意:使用
gcc -Wall -Wpedantic -std=c99和-std=c11,您会收到警告:“警告:ISO C 禁止在函数返回 void [-Wpedantic] 中使用表达式'返回'”。 -
@HolyBlackCat:我可以同时询问 C、C++ 和 Java 吗? ;-)
-
@DevSolar :D 好吧,我会说得更清楚。 IMO 询问 C 和 C++ 中存在的功能是合法的。通常,这些功能在两种语言中的行为相似。如果不是,一个好的答案将描述差异。
标签: c++ c gcc clang language-lawyer