Understanding the operator "less" or "greater" in assigning value with C++

681 Views Asked by At

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 ??
2

There are 2 best solutions below

0
On

The expression

x >= 3

is a pure comparison. It tests, whether the value of variable x is greater than, or equals 3. The result is 0 or 1 – for x equal 2 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 value 2.


In x = x > 3; the subexpression x > 3 is a comparison. Its result is 1 if the comparison succeedes, 0 otherwise.

Since you initialized x to 2, the result of the comparison is false, i.e. zero.

As a result

x = x > 3;

equivalent to

x = (x > 3);

resolves to

x = 0;

hence the output you observed.

0
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.