简体   繁体   中英

Are the following statements equivalent in C?

If my_function() returns a 0 for success or -EINVAL for failure, then would these two statements be equivalent?

if( my_function() ){  

and

if( my_function() == 0){

I'm aware that 1 is boolean True and 0 is boolean False in C, so I wasn't sure if the first statement would fail the if statement if my_function() successfully returned 0.

In C in boolean context expression a is typically equivalent to expression a != 0 . This means that your first variant

if( my_function() ){  

is equivalent to

if( my_function() != 0 ){  

This in turn means that your second variant is not equivalent to the first one. It is actually opposite to the first one. Your first version checks for failure, while the second one checks for success.

According to the C Standard (6.8.4.1 The if statement)

2 In both forms, the first substatement is executed if the expression compares unequal to 0 ....

And (6.5.9 Equality operators)

3 The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.108) Each of the operators yields 1 if the specified relation is true and 0 if it is false....

So the expression in this if statement

if( my_function() ){  

compares unequal to 0 if the function returns a non-zero value.

In this if statement

if( my_function() == 0){

the expression my_function() == 0 compares unequal to 0 if the function returns 0 because in this case the relation is true and yields 1.

So these if statements are opposite each other.

Equivalent if statements would be

if( !my_function() ){

or if to include the header <iso646.h>

if( not my_function() ){

and

if( my_function() == 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM