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 ??
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
x
is greater than, or equals 3. The result is0
or1
– forx
equal2
it 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
x
remains unchanged. Hence the observed resulting value2
.In
x = x > 3;
the subexpressionx > 3
is a comparison. Its result is1
if the comparison succeedes,0
otherwise.Since you initialized
x
to2
, the result of the comparison is false, i.e. zero.As a result
equivalent to
resolves to
hence the output you observed.