I have recently inherited an old project to make some optimization and add new features. In this project I have seen this type of condition all over the code:
if (int_variable)
instead of
if (int_variable > 0)
I have used the first option only with boolean
type of variables.
Do you think the first option is a "correct" way to check if a number is positive?
负数也计算为true
,因此您应该使用if (int_variable > 0)
来检查数字是否为正。
否。第一种选择是检查数字是否为非零的正确方法。
Any non-zero value will be considered true
, so your version with >
is a bit sketchy if the variable truly is int
, ie signed. For clarity I prefer to make that explicit in many cases, ie write
if (int_variable != 0)
This is perhaps a bit convoluted (basically computing a Boolean where one can be automatically inferred), I would never use if (bool_variable == true)
for instance but I think the integer case makes the test clearer. Reading the two cases out loud works way better for the integer.
if (int_variable)
has the same meaning as if (int_variable != 0)
.
This is not the same as if (int_variable > 0)
unless you otherwise know that the value will never be negative.
When using an integer value as a truth value in C, zero yields false
while any non-zero value yields true
.
In your case, assuming int_variable is signed, (int_variable)
is not equivalent to (int_variable > 0)
since int_variable
being negative will yield true
and false
, respectively.
So
if (int_variable) { … }
is not a correct way of checking whether int_variable
is positive.
In C any expression which evaluates to integer 0
or a null pointer is considered false. Anything else is true.
So basically something like
int i = ...;
if ( i )
Test if i
is 0. However, if i
is negative, the condition will also be true, so this is no replacement for i > 0
. Unless i
is unsigned
. Simply because they cannot be negative. But your compiler may warn about such constructs as they often show a wrong concept.
Coming to coding style, if ( i )
is bad style if you are really comparing to the value 0
. You better compare explicitly: if ( i != 0 )
. However, if i
contains some boolean result, you should use a "speaking" name (eg isalpha('A')
to use a ctypes.h
function instead of a variable) and do not compare. Compare the readbility:
char ch = ...;
if ( isalpha(ch) )
if ( isalpha(ch) != 0 )
For the latter you have to think a second about the comparison - unnecessarily.
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.