Search code examples
c++clanguage-lawyerundefined-behavior

Can guaranteed UB be rejected at compile-time?


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


Solution

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

    Yes. The definition of undefined behavior in [defns.undefined] is:

    behavior for which this document imposes no requirements

    [ Note: Undefined behavior may be expected when this document omits any explicit definition of behavior or when a program uses an incorrect construct or invalid 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 ([defns.diagnostic])), to terminating a translation or execution (with the issuance of a diagnostic message). Many incorrect program constructs do not engender undefined behavior; they are required to be diagnosed. Evaluation of a constant expression ([expr.const]) never exhibits behavior explicitly specified as undefined in [intro] through [cpp]. — end note ]