0

Is that for 1 return to True value and 0 return to False value? The output is 111

#include <iostream>
using namespace std;
int main()
{
    int x = 8, y = 10;
    if (x = 2 && y > x)
        cout << y + 1;
    cout << x;
    
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
Gg Ggg
  • 1
  • 1
  • 2
    `x = 2` is an assignment, not a compare. The rest is the result of operator precedence in the computation that provides the value being assigned. – user4581301 Jan 07 '23 at 22:56
  • 2
    Make sure you enable compiler warnings. – chris Jan 07 '23 at 22:56
  • 4
    Since `&&` has higher [operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) than `=`, your condition is being interpreted as `x = (2 && y > x)`, not `(x = 2) && (y > x)` or `(x == 2) && (y > x)` – Nathan Pierson Jan 07 '23 at 22:58
  • 2
    Would it make more sense if you read it as `x = (2 && y > x)` where `true == 1`? – Retired Ninja Jan 07 '23 at 22:58
  • 1
    Right now we're sort of guessing at the answer. What did you expect to happen? Or more important, what did you *need* to happen? – user4581301 Jan 07 '23 at 22:59

1 Answers1

3

As the && operator has a higher operator precedence than the = operator, the condition of the = operator is being treated as assigning a boolean value to x as-if you had written:

x = (2 && (y > x))

Not as:

(x = 2) && (y > x)

For better experiences, use parenthesis explicitly:

if ((x = 2) && (y > x))

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Asjid Ali
  • 57
  • 4