I used greater than and less than signs and it gives ouput! How it is working ?
int x = 2;
x >= 3;
cout << x; // output is 2
And also the output is different like this
int x = 2;
x = x > 3;
cout << x; // output is zero !! HOW ??
I used greater than and less than signs and it gives ouput! How it is working ?
int x = 2;
x >= 3;
cout << x; // output is 2
And also the output is different like this
int x = 2;
x = x > 3;
cout << x; // output is zero !! HOW ??
On
If you use
int x = 2;
x >= 3;
cout << x;
the output is 2 because the result of the x >= 3 operation is discarded (not used) and x remains by the same value as it were initialized. x was not assigned by any value after its initialization.
If you use
int x = 2;
x = x > 3;
cout << x; `
x is checked whether it is greater than 3 or not with x > 3. If it is, the value of the expression x > 3 turns 1, if not it turns 0. Comparison operations are boolean expressions.
This boolean value is assigned back to x after the evaluation of x > 3.
Since x is not greater than 3, the expression x > 3 gains the value 0 and this value is assigned back to x and finally what is printed.
The expression
is a pure comparison. It tests, whether the value of variable
xis greater than, or equals 3. The result is0or1– forxequal2it is zero, false.Terminating the expression with a semicolon creates a statement. That statement performs a comparison and ...nothing else. The result of comparison is discarded, and the variable
xremains unchanged. Hence the observed resulting value2.In
x = x > 3;the subexpressionx > 3is a comparison. Its result is1if the comparison succeedes,0otherwise.Since you initialized
xto2, the result of the comparison is false, i.e. zero.As a result
equivalent to
resolves to
hence the output you observed.