0

Look at the following code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) 
{
    int i = 2;
    srand(time(NULL));
    if (rand() % 2 == 0)
        i = i++ + 2;
    printf("%d", i);
}

Now, sometimes the output of this program is 2 while sometimes it is 4— (Now, this value 4 depends on the compiler and the value be different on a different compiler, provided that the undefined statement i = i++ + 2; is executed) — with the issuance of a warning in both the cases. So, when I get the output 2 the statement i = i++ + 2; is not executed by the compiler.

So does my program encounter an undefined behavior in that case too, even if the statement is not executed since the compiler(GCC, in my case) issue a warning with it?

  • 1
    A warning is just a diagnostic message issued by the compiler, which may or may not be mandated by the C specification. But a warning message from the compiler doesn't mean it won't attempt to generate code for the program, or omit what it warned about. It's your responsibility as the programmer to make sure there's no UB in the code you pass to the compiler. – Some programmer dude May 06 '20 at 08:15
  • @Some programmer dude So is the behavior undefined for the case where I am getting output ```2```? –  May 06 '20 at 08:18
  • @usr The problem here is that the code in this question is quite a little bit different from the one in the duplicate question and especially because of the `rand()` function. It shall be looked at separately if the code actually isn´t executed or if it is. We can´t know. And with that, one can´t mention that the code didn´t were executed. Maybe a bit specific, but a notable difference. – RobertS supports Monica Cellio May 06 '20 at 08:31
  • @RobertSsupportsMonicaCellio It's two cases: when the branch is taken and when not. When the branch is taken is taken, it's UB obviously. So the question is whether it's UB when the branch is not taken and that's what addressed in the dupe. – P.P May 06 '20 at 08:53

1 Answers1

2

Undefined Behavior happens at runtime, not at the static code level, if that makes sense.

If you have a valid path and and invalid path in your program like in your example, the entire execution of the program is UB if at any point it takes the invalid path.

So if you never execute over an invalid statement then you have defined behavior.


Note: I use "invalid code" to mean code that would cause UB

bolov
  • 72,283
  • 15
  • 145
  • 224