gpt4 book ai didi

c - 当使用一个没有参数的前向声明的 C 函数时,到底什么是未定义的?

转载 作者:太空宇宙 更新时间:2023-11-04 05:32:21 24 4
gpt4 key购买 nike

在摆弄 C 的旧的奇怪兼容性行为时,我最终得到了这段代码:

#include <stdio.h>
int f();
int m() {
return f();
}
int f(int a) {
return a;
}
int main() {
f(2);
printf("%i\n", m());
}

我确定 m() 中对 f() 的调用是未定义的行为,因为 f() 应该完全正确一个参数,但是:

  • 在 x86 上,除了使用 GCC 和 -O3。没有 -O3 时输出为 2,有它时为 0。在 Windows 上,MSVC 不会打印任何错误,程序只会输出随机数。
  • 在 ARM(Raspberry Pi 3)、GCC 6.3.0 和 clang 3.8.1 上,我观察到相同的错误行为,选项 -O3 仍然输出 0,但正常编译导致 2使用 GCC 和... 66688 使用 clang。

当出现错误消息时,它几乎就是您所期望的:(非常有趣,因为 a 没有出现在打印行中)

foo.c: In function ‘m’:
foo.c:4:9: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
return f();
^~~
foo.c: In function ‘main’:
foo.c:11:2: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
printf("%i\n", m());

我的猜测是 -O3 导致 GCC 内联调用,从而使其明白发生了问题;并且堆栈或寄存器中的剩余部分被用作调用的参数。但是它怎么还能编译呢?这真的是(非)预期的行为吗?

最佳答案

具体违反的规则是C 2018 6.5.2.2 (Function calls) 6:

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions. If the number of arguments does not equal the number of parameters, the behavior is undefined.…

由于这不是约束,因此编译器不需要生成诊断信息——C 标准完全未定义该行为,这意味着该标准根本没有强加任何要求。

由于标准没有强加任何要求,因此忽略问题(或未能识别问题)和诊断问题都是允许的。

关于c - 当使用一个没有参数的前向声明的 C 函数时,到底什么是未定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com