Can a 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 does not have UB until the user enters any numbers outside the range 0 - 4 .

However, according to this topic , UB may go back in time. Now consider this program:

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

Any call to this program leads to undefined behavior, and since it can move in time, all the behavior of this program for any call to undefined. Can a compiler refuse a program and not generate an executable file? (We could say that UB returns on time to the compilation stage!)

+6
c ++ c undefined-behavior language-lawyer
Dec 19 '14 at 9:51
source share
2 answers

Can a compiler refuse a program and not generate an executable file?

Yes. Undefined behavior definition:

for which this International Standard does not impose any requirements [Note: undefined behavior can be expected if there is no explicit definition of behavior in this International Standard or when the program uses an erroneous construction or erroneous data. Acceptable undefined behavior varies from completely ignoring the situation with unpredictable results, maintaining during a translation or program execution in a documented manner specific to the environment (with or without a diagnostic message), until the translation or execution is stopped (with a diagnostic message). Many erroneous software constructs do not generate undefined behavior; they must be diagnosed. - final note]

+13
Dec 19 '14 at 9:53 on
source share

To add to Jonathan's answer.

The second program invokes undefined behavior, and the compiler has the right to stop the translation, because undefined behavior is unlimited (c11, 3.4.3p1).

The first program can cause undefined behavior, but the compiler cannot stop the translation, because not all execution paths produce undefined behavior.

In Defect Report No. 109 , C, the Committee says:

In addition, if any possible execution of this program leads to undefined behavior, this program will not be strictly consistent. An appropriate implementation should not translate a strictly appropriate program simply because some possible execution of this program will lead to undefined behavior.

+4
Dec 19 '14 at 15:53
source share



All Articles