在 C 中调用空函数是否会调用 UB?

问题描述 投票:0回答:2
#include <stdio.h>

static int foo(){}

int main(){
  if (foo()) {
    printf("OK\n");
  }
  return 0;
}

我不太确定是否中止该操作,而且我在 ISO/IEC 9899:1999 (E) 中还没有找到任何解释。也许我错过了。 那么,在这种情况下,

if(foo())
就是 UB 吗?

我用gcc7.3 aarch64-linux进行测试。

-O0
:打印正常
-
O1
-O3
:不打印任何内容

c undefined-behavior
2个回答
3
投票

C17 6.9.1 §12

如果到达终止函数的

}
,并且函数调用的值被调用者使用,则行为未定义。

调用者正在使用函数的值作为

if
评估的一部分,因此您的代码会调用未定义的行为。自第一个 C 标准以来,情况一直如此。


-1
投票

编译 C 程序时,应始终启用警告。使用 GCC,您可以通过添加选项

-Wall
:

来做到这一点
$ gcc -Wall test.c
test.c: In function ‘foo’:
test.c:3:1: warning: no return statement in function returning non-void [-Wreturn-type]
    3 | static int foo(){}
      | ^~~~~~
© www.soinside.com 2019 - 2024. All rights reserved.