Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 237
M.M Avatar asked Dec 19 '14 09:12

M.M


Video Answer


1 Answers

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 ]

like image 75
Jonathan Wakely Avatar answered Oct 11 '22 13:10

Jonathan Wakely