Testing Boolean Conditions
suggest changeIn a controlling expression such as an if condition, zero is false and any nonzero value is true. Do not compare an arbitrary logical value with true: true represents the value 1, while another true value may be different.
#include <stdbool.h>
#include <stdint.h>
bool upper_bit_is_set(uint8_t bits)
{
return (bits & UINT8_C(0x80)) != 0;
}
The explicit != 0 documents that the masked result is being converted to a Boolean result. In an if statement, the direct form is also correct:
if (bits & UINT8_C(0x80)) {
/* The high bit is set. */
}
By contrast, (bits & 0x80) == true is false when the masked value is 0x80, because 0x80 is not equal to 1.
C99 through C17 provide bool, true, and false as macros in <stdbool.h>, with _Bool as the underlying language type. C23 makes bool, true, and false language features.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents