Skip to main content

True and False in C

Now we come to an advanced trick which you do need to know about, but if it only confuses you, come back to this bit later. Most experienced C programmers would wince at the expression if(a!=0).

The reason is that in the C programming language dosen't have a concept of a Boolean variable, i.e. a type class that can be either true or false. Why bother when we can use numerical values. In C true is represented by any numeric value not equal to 0 and false is represented by 0. This fact is usually well hidden and can be ignored, but it does allow you to write

if(a != 0) just as if(a)

because if a isn't zero then this also acts as the value true. It is debatable if this sort of shortcut is worth the three characters it saves. Reading something like

if(!done)

as 'if not done' is clear, but if(!total) is more dubious.