Search code examples
cundefined-behavior

Is a program well defined before the line that causes undefined behavior?


Consider this code:

int main()
{
    printf("Hello World!\n");
    int i;
    i = i++ + ++i; // UB
}

Is this code guaranteed to print "Hello World!"? The last line invokes undefined behavior, but does that invalidate the whole program?

I found this but that question is about C++. This is about C.

It's not a dup of Undefined behavior and sequence points since it's C++. The answer may or may not be the same, but this question is about C.


Solution

  • From the C standard (3.4.3) :

    undefined behavior

    behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

    Followed by :

    NOTE Possible 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).

    This means the standard does not impose any guarantees on the behavior of the entire program - including "earlier" operations.

    Specific implementations however, might add certain guarantees for certain instances of undefined behavior (consult your compiler documentation eg.). And in practice, many implementations do behave in the way you describe for the most part. Optimizations tend to make this difficult to guarantee though. Additionally, compilers sometimes eliminate entire branches if they contain undefined behavior.