Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between NOT false and true

Tags:

c

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?

like image 546
user3475003 Avatar asked Dec 01 '22 00:12

user3475003


2 Answers

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?)

like image 57
Wouter van Ooijen Avatar answered Dec 05 '22 06:12

Wouter van Ooijen


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.

like image 33
Eugene Sh. Avatar answered Dec 05 '22 05:12

Eugene Sh.