Can guaranteed UB be rejected at compile-time?

让人想犯罪 __ 提交于 2019-12-22 04:16:04

问题


Consider this program:

#include <stdio.h>

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

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.

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

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

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!)


回答1:


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 ]




回答2:


To add to Jonathan's answer.

The second program invokes undefined behavior and a compiler has the right to stop the translation as undefined behavior is not bounded (c11, 3.4.3p1).

The first program may invoke undefined behavior but the compiler cannot stop the translation as not all execution paths produce undefined behavior.

In Defect Report #109, C Committee says:

Furthermore, if every possible execution of a given program would result in undefined behavior, the given program is not strictly conforming. A conforming implementation must not fail to translate a strictly conforming program simply because some possible execution of that program would result in undefined behavior.



来源:https://stackoverflow.com/questions/27563431/can-guaranteed-ub-be-rejected-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!