1

I am working toward my C++ exam, and I am doing some past papers. Then I stumbeled over this code understanding task. And I am wondering, why doesn't value change to 4 in this if statement?

int found = 0, value = 5;
if (!found || --value == 0) {
    cout << "danger";
}
cout << "value =" << value << endl;
Baum mit Augen
  • 47,658
  • 24
  • 139
  • 177

2 Answers2

8
if (!found || --value == 0)

In Logical OR operation, if first condition is satisfied, then it won't evaluate second condition. Here !found is TRUE and it won't execute --value thus leaving it's value as 5.

Srikanth
  • 131
  • 8
0

Because if the first condition is satisfied, the second is not even considered to evaluate. To get your expectations, swap the conditions.

int found = 0, value = 5;
if ( --value == 0 || !found) {
    cout << "danger";
}
cout << "value =" << value << endl;
Eduard Rostomyan
  • 6,736
  • 1
  • 29
  • 67