#include <iostream>
using namespace std;
int main() {
float a =5;
a = !5 < a;
cout<<a;
return 0;
}
this gives output " 1 ", help me out to understand this.
!something_here
will evaluate to 0
except the case when something_here
is 0
.
Since 0 < a
, ( 0 < 5
), a
gets a value of true
, which is 1
, when parsed as float.
!5 < a;
This is a boolean expression, resulting in true
or false
, when casting true
to an integer or float in this case, it results in 1
, casting false
gives you 0
.
To make the code a bit more understandable this is roughly equivalent:
float a =5;
bool check = !5 < a;
if(check)
a = 1;
else
a = 0;
cout<<a;
The expression evaluates to true
because !5 == 0
and 0 < a
is true
.
Expression a = !5 < a;
is equivalent to a = (a > 0)
, and since a
is initialized with 5
, (a > 0)
gives true
, which is converted to float value 1
then.
So why is a = !5 < a;
equivalent to a = (a > 0)
? Expression !5
is equivalent to (5 == 0)
, which is obviously false
. false
, when used in a comparison with a float value is converted to 0
, and 0 < a
is - at least for built-in data type float - equivalent to (a > 0)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.