Stack Overflow Asked by Sajawal Bashir on December 11, 2021
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.
Answered by RobertS supports Monica Cellio on December 11, 2021
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.
Answered by CiaPan on December 11, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP