-3

Consider the following

int main() {
    int a = 8;
    int b = 10;

    while (true) {
        if (a /= 2 && b < 12) {
            b++;
            std::cout << b << std::endl;
        }
        else break;
    }

    return 0;
}

Now c++ is not my main language, but how does c++ evaluate this if statement?

In this case, when b>=12, the compiler throws the "division by zero" exception, but why?

Now if i wrap the states in parentheses i do not get the exception.

if( (a /= 2) && (b < 12))

Does this have something to do with how c++ evaluates the statements?

If evaluation is not the problem:

I am aware of that

a = (a/2 && b<12)

would not hold either.

P Λ Q does not hold for P Λ ¬Q but the state of P should not be affected? Why is it P gets blamed instead of ¬Q?

JohEker
  • 627
  • 5
  • 13
  • *"I could not try this in java because java does not allow integers to be represented as boolean values in the same way*" - well, just add the ` != 0` and you are good to go. In `C++`, any integer different than `0` evaluates to `true`, so it's not a big problem to simulate this behaviour in `Java` – Fureeish Jun 12 '18 at 23:10
  • @Fureeish well i was not sure on weather java would evaluate it in the same way, therefore i did not want to draw any conclusions trying to force the example on java – JohEker Jun 12 '18 at 23:13
  • @HolyBlackCat Ah yes that's true. Assignment of any kind have the next-lowest [operator precedence](http://en.cppreference.com/w/cpp/language/operator_precedence) of any operators. You might want to add that as an answer. – Some programmer dude Jun 12 '18 at 23:14

1 Answers1

2
if (a /= 2 && b < 12)

is the same as:

if (a /= (2 && b < 12))

so:

  • 2 is evaluated, which is converted to true in the context of an operand to &&. This does not trigger short-circuit evaluation so we continue...
  • b < 12, which in the case you're talking about is false
  • So 2 && b < 12 evaluates to false overall
  • a /= 2 && b < 12 is therefore equivalent to a /= false here, which is equivalent to a /= 0.
Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49