Quick question on If(!x()) where x() is a function
Guys, I am not exactly sure what happens here for the if statement. I did a bunch of google sea开发者_高级运维rches, but nothing comes up. Obviously, the function x() returns something. Either a 1 or a 0. But I am not sure what it does. Is it short hand for x() == 0 or x() == 1. I am just going over coding examples and I noticed it.
if(!x())
{
// executes if x() is 0
// x() == 0
}
if(x())
{
// executes if x() is non-0
// x() != 0
}
It is short hand for if(x()==0){ // stuff }
Note that x()
does not have to return only '0' or '1'. In C, any non-zero value is considered TRUE in a conditional statement and the negation of any non-zero value is ZERO.
if(!x())
just checks if x()
returns something that evaluates to false, in other words if(x() == false)
or if(x() == 0)
is the same.
That means x() == 0
. And if (x())
means if (x()!=0)
In C, 0 is considered false and all other numbers are considered true. In you if-statement, you are saying "if x()
is not true" which is equivalent to "if x()
is false". Therefore, if(!x())
is the same thing as if(x()==0)
.
精彩评论