How does C handle non-booleans in an if statement?

827 views Asked by At

I sometimes see this in a C program (I'm using the C18 compiler):

unsigned char someValue = getSomeDataFromSomewhere();
if (someValue) {
    doStuff();
} else {
    doOtherStuff();
}

I know what happens when you give an if loop a boolean (unsigned in the C18 compiler), but what happens when you put a non-boolean in?

My guess: it does doStuff() when the value isn't zero, and doOtherStuff() when the value is zero. But I don't know this, so I'd like to get some reference.

2

There are 2 answers

0
msam On BEST ANSWER

your guess is right:

from §6.8.4.1 of WG14/N1256

the first substatement is executed if the expression compares unequal to 0

0
K Scott Piel On

Simply put -- if it is non-zero, it is true. If it is zero, it is false.