gpt4 book ai didi

c - 有没有办法预测未定义的行为或实现定义的行为?

转载 作者:行者123 更新时间:2023-12-02 08:52:00 25 4
gpt4 key购买 nike

#include<stdio.h>
int main(void)
{
int i=5;
printf("%d", i++ + ++i);
return 0;
}

我知道这是未定义的行为(或定义的实现),不应使用。但是编译器确实在没有给出任何警告的情况下给出了输出。那么有没有什么可以预测程序的输出呢?

最佳答案

有没有办法预测未定义的行为

没有

未定义的行为 意味着编译器不需要遵守任何特定的行为,每个编译器可能会或可能不会显示相同的行为。您不能依赖编译器对未定义行为的近似/预测输出并以此为基础编写代码。

严格来说,避免编写任何调用未定义行为的代码。

引用:

未定义行为 (UB) 由 ISO/ANSI C 标准定义为:

behavior, upon use of a nonportable or erroneous program construct, of erroneous data, or of indeterminately valued objects, for which this International Standard imposes no requirements.
NOTE: Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

有什么方法可以预测实现定义的行为

是的,如果可移植性(确保您的解决方案以相同的方式跨不同的编译器工作)不是您关心的问题。
不,如果您正在寻找便携性。

如果您正在使用特定的编译器,并且您的解决方案/项目只需要为该特定的编译器和环境工作,那么您可以自由使用该编译器显示的实现特定行为该环境下的编译器。


这应该是一篇有趣的读物:

A Guide to Undefined Behavior in C and C++.

关于c - 有没有办法预测未定义的行为或实现定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7811803/

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