有什么方法可以预测未定义的行为或实现的已定义行为? [英] Is there any way to predict the undefined behaviour or implementation defined behaviour?

查看:93
本文介绍了有什么方法可以预测未定义的行为或实现的已定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I know this is undefined behaviour (or implementation defined) and should not be used. But the compiler does give an output without giving any warning. So is there any to predict the program's output?

推荐答案

有什么方法可以预测未定义的行为?

未定义的行为表示编译器不需要遵循任何特定的行为,每个编译器可能会或可能不会显示相同的行为.您不能依靠逼近/预测来自编译器的未定义行为的输出,而不能以此为基础编写代码.

Undefined Behavior means that compiler does not need to adhere to any specific behavior, every compiler may or may not show the same behavior. You cannot rely on approximating/predicting outputs of Undefined behavior from the compiler and write a code on the basis of that.

请严格避免编写任何调用未定义行为的代码.

Strictly, avoid writing any code which invokes Undefined Behavior.

参考:

未定义行为(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).

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

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

Is there any way to predict Implementation defined behaviour?

Yes, If Portability(assurance that your solution works across different compilers in same way) is not your concern.
No, If you are looking for portability.

如果您正在使用特定的编译器,并且您的解决方案/项目仅需要针对该特定的编译器和环境运行,则您可以 自由使用该显示的特定于实现的行为该环境上的编译器.

If you are working on a specific compiler then,and your solution/project needs to only work for that particular compiler and environment then you can take the liberty to use the implementation specific behavior displayed by that compiler on that environment.

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

This should be an Interesting read:

有关C和C ++中未定义行为的指南.

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

这篇关于有什么方法可以预测未定义的行为或实现的已定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆