简体   繁体   中英

Difference between NOT false and true

I have this chunk of code:

if ( ( data.is_err != FALSE ) && ( available != FALSE ) )
    {
        Set_Dtc_TimerChange(DTC_VPOS, +dt_ms);
    }

Why would you use not equal to false instead of just equal to true? Is there a difference at all?

This is a C question rather than an EE, but as C is very close to the hardware....

The old C definition of false is 0, with all other values being true , that is

if( 0 ){ ... }

will not execute the ... code, but for instance

if( 1 ){ ... }
if( -1 ){ ... }
if( 42 ){ ... }

all will. Hence you can test a truth value for being equal to FALSE (which is defined as 0), but when you want to compare it to true, which value would you use for true? Some say TRUE must be defined as (!FALSE), but that would yield -1, which is a value of true, but not the only one.

Hence programmers tended to avoid conparing to TRUE.

Modern C should have solved this by defining TRUE to be (I think) 1, but that stil has funny consequences, like

int probably( void ){ return 42; }
if( probably() ){ ... }
if( probably() == TRUE ){ ... }

Here the blame is on probbaly(), which returns an abiguous truth value.

Personally, I would have written

if ( data.is_err && available ) { ... }

which I think is much more readable and avoids the comparisons.

(BTW how can something be available when there is a data error?)

This code can be safely replaced by:

if (  data.is_err &&  available ) { 
    Set_Dtc_TimerChange(DTC_VPOS, +dt_ms); 
}

unless the FALSE has some non-traditional definition somewhere in the program. A good compiler will produce equivalent code for either form, but the more readable one is preferred.

C does not have a Boolean type. Instead, it treats 0 as false and any other value as true. As a result, there is no value that you can test against to determine whether a value represents true. That's not important if you write idiomatic C code: if (x) ... will always do the right thing. Folks who are uncomfortable with this idiom like to test explicitly against some representation of false, but never explain why they limit that to one level. After all, x != FALSE is just a value, and by the same argument needs to be tested: if ((x != FALSE) != FALSE)... .

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