C Language Checking logical expression against 'true'


Example

The original C standard had no intrinsic Boolean type, so bool, true and false had no inherent meaning and were often defined by programmers. Typically true would be defined as 1 and false would be defined as 0.

C99

C99 adds the built-in type _Bool and the header <stdbool.h> which defines bool (expanding to _Bool), false and true. It also allows you to redefine bool, true and false, but notes that this is an obsolescent feature.

More importantly, logical expressions treat anything that evaluates to zero as false and any non-zero evaluation as true. For example:

/* Return 'true' if the most significant bit is set */
bool isUpperBitSet(uint8_t bitField)
{
    if ((bitField & 0x80) == true)  /* Comparison only succeeds if true is 0x80 and bitField has that bit set */
    {
        return true;
    }
    else
    {
        return false;
    }
}

In the above example, the function is trying to check if the upper bit is set and return true if it is. However, by explicitly checking against true, the if statement will only succeed if (bitfield & 0x80) evaluates to whatever true is defined as, which is typically 1 and very seldom 0x80. Either explicitly check against the case you expect:

/* Return 'true' if the most significant bit is set */
bool isUpperBitSet(uint8_t bitField)
{
    if ((bitField & 0x80) == 0x80) /* Explicitly test for the case we expect */
    {
        return true;
    }
    else
    {
        return false;
    }
}

Or evaluate any non-zero value as true.

/* Return 'true' if the most significant bit is set */
bool isUpperBitSet(uint8_t bitField)
{
    /* If upper bit is set, result is 0x80 which the if will evaluate as true */
    if (bitField & 0x80)
    {
        return true;
    }
    else
    {
        return false;
    }
}