Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C is there any guarantee with code prior to undefined behavior?

Tags:

c

standards

In the following code is is guaranteed that "0\n" be printed?

#include <stdio.h>
int main(void)
{
    int c = 0;
    printf("%d\n",c);

    printf("%d,%d\n",++c,++c);
}

More generally, if a program has undefined behavior does the entire program become undefined or only from the sequence point that begins the problematic code?

Please note: I am not asking about what the compiler does with the second printf. I am asking if the first printf is guaranteed to occur.

I know that undefined behavior is capable of blowing up your computer, crashing your program, or whatnot.

like image 844
Good Person Avatar asked Oct 23 '10 02:10

Good Person


People also ask

What causes undefined Behaviour in C?

In C the use of any automatic variable before it has been initialized yields undefined behavior, as does integer division by zero, signed integer overflow, indexing an array outside of its defined bounds (see buffer overflow), or null pointer dereferencing.

What does undefined behavior mean in C?

Undefined Behavior in C and C++ So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.


1 Answers

Well even ignoring things like "Anything could happen! the program could travel back in time and prevent itself from running in the first place!", it's perfectly possible for a compiler to detect some forms of undefined behavior and not compile in that case in which case you'll wouldn't have gotten it to run in the first place. So yes, undefined behavior is contagious in principle if not necessarily so in practice most of the time.

like image 191
Logan Capaldo Avatar answered Nov 06 '22 18:11

Logan Capaldo