-3

Why are these two statements not equivalent?

If i==3 then the fork() is executed.

If i!=3 then the fork() doesn't get executed.

What is going on here? Is it some kind of compiler optimization malfunction?

if((i==3) && (fork()==0))
if((fork()==0) && (i==3))
jkbx
  • 414
  • 1
  • 6
  • 21
  • My guess would be that once the first value is false, it has no need to check the next. I'm not a C programmer. – Bob Mar 30 '15 at 17:49

3 Answers3

1

This is called short-circuit evaluation. If the first term is false, you know the whole && will be false, so many languages skip the second evaluation deliberately.

Luke
  • 7,110
  • 6
  • 45
  • 74
0

This is the direct result of short-circuit evaluation performed by logical && operator: when i != 3, if statement knows that the result of the expression is going to be false, and stops right there.

That's why it does not get to execute fork. If you do not want this behavior, you could use bitwise AND operator &.

However, the logic of your code would remain questionable, because it would be impossible to tell on what side of the "fork" you landed when i != 3.

If you want to do a fork no matter what the value of i, but properly get the side of the "fork", do the fork upfront, and check the result inside the if:

pid_t side = fork();
if (i == 3) {
    if (side == 0) {
        ...
    } else {
        ...
    }
} else {
    if (side == 0) {
        ...
    } else {
        ...
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

The right hand side of C's && operator is not executed when the left hand side is falsey.

skagedal
  • 2,323
  • 23
  • 34