可以保证在编译时拒绝UB吗? [英] Can guaranteed UB be rejected at compile-time?

查看:90
本文介绍了可以保证在编译时拒绝UB吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此程序:

#include <stdio.h>

int main(void)
{
    int x;
    while ( 1 == scanf("%d", &x) )
        printf("%c\n", "hello"[x]);
}

只要用户没有输入0-4范围之外的任何数字,编译器就必须成功编译此代码,因为该程序没有UB.

The compiler must compile this successfully because the program has no UB so long as the user does not enter any numbers outside the range 0-4.

但是,根据此线程 UB可以及时返回.现在考虑这个程序:

However, according to this thread UB can travel back in time. Now consider this program:

int main(void)
{ 
    printf("hello\n");
    "hello"[6];
}

对该程序的任何调用都会导致未定义的行为,并且由于这可能会花费时间,因此该程序在任何调用上的整个行为都是不确定的.因此,编译器可以拒绝程序而不生成可执行文件吗? (我们可以说UB会回到过去的编译阶段!)

Any invocation of this program results in undefined behaviour, and since that can time-travel, the entire behaviour of this program on any invocation is undefined. Can the compiler therefore reject the program and not generate an executable? (We might say that the UB travels back in time to the compilation stage!)

推荐答案

编译器是否可以因此拒绝程序并且不生成可执行文件?

Can the compiler therefore reject the program and not generate an executable?

是的.未定义行为的定义是:

Yes. The definition of undefined behaviour is:

本国际标准未规定的

行为 [注:当本国际标准省略行为的任何明确定义或程序使用错误的构造或错误的数据时,可能会出现未定义的行为.允许的未定义行为 范围从完全忽略具有不可预测结果的情况,到以环境特征的文档化方式在翻译或程序执行期间的行为(有或没有发出诊断消息),到终止翻译或执行(有发行) .许多错误的程序构造不会引起未定义的行为;他们需要被诊断. —尾注]

behavior for which this International Standard imposes no requirements [ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible 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). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. — end note ]

这篇关于可以保证在编译时拒绝UB吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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