user1544337
user1544337

Reputation:

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

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.

Upvotes: 2

Views: 940

Answers (2)

msam
msam

Reputation: 4287

your guess is right:

from §6.8.4.1 of WG14/N1256

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

Upvotes: 5

K Scott Piel
K Scott Piel

Reputation: 4380

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

Upvotes: 7

Related Questions