这将在没有任何警告的情况下编译.

这在C和C++中是合法的,还是只在GCC和Cang中有效?

如果它是合法的,它是C99之后的新事物吗?

void f(){

}

void f2(){
    return f();
}

Update

正如《雷克萨斯》所说,我试过:

$ 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)

Update

有人问这个建筑有什么帮助.嗯,或多或少是语法上的糖分.下面是一个很好的例子:

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");
}

推荐答案

C11,6.8.6.4"百年宣言":

带有表达式的return语句不得出现在返回类型为void的函数中.

No,即使表达式是void类型,也不能使用.

同一份文件的前言:

第二版的主要变化包括:

[.]

  • return不带返回值的函数中不允许的表达式(反之亦然)

So this was a change from C89 -> C99 (the second edition of the language standard), and has been that way ever since.


C++14、6.6.3"return声明":

A return statement with an expression of non-void type can be used only in functions returning a value [.] A return statement with an expression of type void can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller.

Yes,可以使用表达式if,它是void类型(自C++98以来一直有效).

C++相关问答推荐

为什么下面的递归基本情况在C中不起作用?

数据包未从DPDK端口传输到内核端口

ZED for SDL上的C语言服务器

为什么C语言允许你使用var =(struct NAME){

在C语言中,在数学运算过程中,为什么浮点数在变量中的行为不同

向上强制转换C中的数值类型总是可逆的吗?

指向不同类型的指针是否与公共初始序列规则匹配?

是否定义了此函数的行为?

如何在双向表中实现线程安全,每个条目仅使用4位,同时避免任何全局锁?

我编写这段代码是为了判断一个数字是质数、阿姆斯特朗还是完全数,但由于某种原因,当我使用大数时,它不会打印出来

Makefile无法将代码刷新到ATmega328p

我正在使用c学习数据 struct ,在学习堆栈时,我试图将中缀转换为后缀,并编写了这段代码.代码未给出输出

Malloc和对齐

浮点正零何时不全为零?

";错误:寄存器的使用无效;当使用-masm=intel;在gcc中,但在AT&;T模式

为什么孤儿进程在 Linux 中没有被 PID 1 采用,就像我读过的一本书中声称的那样?

我们可以在不违反标准的情况下向标准函数声明添加属性吗?

inline 关键字导致 Clion 中的链接器错误

2 个经过restrict修饰的指针可以比较相等吗?

我如何修复我的代码以防止 CS50 第 2 周的复数问题中的 2 个错误?