Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 135 ยท Variables and Types

Booleans

Learn how C represents true and false - zero and non-zero, _Bool and stdbool.h, the C23 bool keywords, why comparisons return int, and common boolean bugs.

A Boolean value is either true or false. Programs are full of them: is the file open, did the user say yes, is this number prime, has the game ended? Every if and every loop depends on one.

C took a long road to a proper Boolean type. For its first 27 years the language had none at all: programmers used int, with 0 meaning false and anything else meaning true. C99 added the _Bool type and the <stdbool.h> header, and C23 finally made bool, true and false real keywords. All three styles still appear in code you'll read, and the old "zero is false" rule still drives every condition in the language, so this lesson covers all of them.

Zero is false, everything else is true

C's conditions don't require a Boolean. An if, while, for or ?: accepts any scalar value (a number or a pointer) and asks one question: is it zero?

  • A value equal to zero (0, 0.0, the null character '\0', a null pointer) counts as false.
  • Any other value (1, -3, 0.001, 'A', a valid pointer) counts as true.
C Truthiness in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This is why C code is full of idioms like while (*p) (loop until the null character at the end of a string), if (!ptr) (if the pointer is null) and if (count) (if anything was counted). They're all shorthand for comparing with zero. nullptr is C23; the Pointers lesson explains it and the older NULL.

The bool type

C99 introduced a dedicated type, _Bool. It can hold only 0 or 1, and it has one special conversion rule: any non-zero value becomes 1. The odd name with an underscore and capital letter was chosen so it couldn't clash with the many programs that had already defined their own bool.

To make it pleasant to use, C99 also added <stdbool.h>, which defines three macros: bool (for _Bool), true (1) and false (0). In C23 bool, true and false are proper keywords, so you don't need the header any more, and true and false now have type bool instead of int.

Standard How you write it
C89/C90 No Boolean type: use int with 0 and 1
C99, C11, C17 _Bool, or #include <stdbool.h> for bool, true, false
C23 bool, true, false are keywords; <stdbool.h> is still allowed but does nothing useful

If your code must compile on pre-C23 compilers, keep #include <stdbool.h>. It's harmless in C23, so including it is the most portable choice.

C Using bool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

printf has no specifier for bool. A bool passed to printf is promoted to int, so %d prints 1 or 0. To print words, use the conditional operator: leap ? "true" : "false". Functions that answer a yes/no question, like is_leap_year, should return bool and have a name that reads like a question (is_, has_, can_).

Conversion to bool is special

Converting a value to bool is not the same as converting it to an integer type. An integer conversion truncates; a bool conversion asks "is it non-zero?":

C Converting to bool versus int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

That rule makes bool safer than the old int flags. With a home-made typedef unsigned char my_bool;, storing the value 256 would give 0, turning "true" into "false". A real bool always gets 1.

Comparisons and logical operators return int

Here's a detail that surprises many people: the relational operators (<, >, <=, >=), the equality operators (==, !=) and the logical operators (&&, ||, !) all produce a value of type int, not bool, even in C23. The value is always exactly 0 or 1, though, so you can store it in a bool or do arithmetic with it.

C What comparisons produce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last three lines show a real trap. isdigit returns some non-zero value for a digit, and on our server that value is 2048. Comparing it with 1 gives false, even though '7' is clearly a digit. !!x (double negation) is a common idiom for turning any value into exactly 0 or 1.

Never compare with true. Write if (is_ready) and if (!is_ready), not if (is_ready == true). With a real bool the comparison happens to work, but with an int flag or a library result like isdigit, == true means == 1 and silently fails for other non-zero values.

Short-circuit evaluation

&& and || evaluate their right operand only when they need it. In a && b, if a is false the whole expression is false, so b is never evaluated. In a || b, if a is true, b is skipped. This lets you write guards like:

C
if (count != 0 && total / count > 10) { /* safe: no division by zero */ }
if (ptr != nullptr && ptr->ready)     { /* safe: no null dereference */ }

The full rules, including precedence between && and ||, are in Comparison and Logical Operators.

Common Boolean bugs

  • = instead of ==. if (x = 0) assigns 0 to x and then tests 0, which is always false. GCC warns ("suggest parentheses around assignment used as truth value") with -Wall. The if statements lesson covers it.
  • Bitwise instead of logical. & and | don't short-circuit and work on bits: 2 & 1 is 0, though both values are "true". Use && and || for conditions.
  • Chained comparisons. if (0 < x < 10) doesn't mean what it does in math. It computes (0 < x), which is 0 or 1, and then compares that with 10, which is always true. Write if (0 < x && x < 10).
  • Incrementing a bool. flag++ on a bool sets it to true (and flag-- toggles it), but GCC warns about both. Assign true, false or !flag instead.
  • Negating the wrong thing. !x == 5 means (!x) == 5, because ! binds tighter than ==. Write x != 5. See Operator Precedence.

Boolean flags in practice

A bool takes one byte, which is fine for individual variables and struct members. When you need many flags packed together, for example 32 permissions in one number, use the bits of an unsigned integer instead. That technique is the topic of Bitwise Operators and Bit-Fields.

Here is a typical use of a bool as a "found" flag in a search loop:

C
bool found = false;
for (size_t i = 0; i < count && !found; i++) {
    if (items[i] == target) {
        found = true;
    }
}

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int n = -1; if (n) { puts("yes"); } else { puts("no"); } What is printed?

    In C, every non-zero value is true in a condition, including negative numbers. Only zero is false.
  2. 2. bool b = 0.25; What value does b hold?

    Conversion to bool tests for non-zero rather than truncating. 0.25 isn't zero, so b becomes 1 (true).
  3. 3. What is the type of the expression 3 < 4 in C23?

    Relational, equality and logical operators produce an int with value 0 or 1 in every C standard, including C23. Only the constants true and false became bool in C23.
  4. 4. Why is if (isalpha(c) == true) a bug?

    The ctype functions only promise a non-zero result for true. On our server isalpha returns 1024 for letters, so the comparison with true (1) fails. Write if (isalpha(c)).
  5. 5. With int x = 50;, what does 0 < x < 10 evaluate to?

    C evaluates it as (0 < x) < 10. The inner comparison gives 1, and 1 < 10 is 1. To test a range, write 0 < x && x < 10.

Summary

  • In conditions, zero (including 0.0, '\0' and null pointers) is false and every other value is true.
  • C99 added _Bool and <stdbool.h> (bool, true, false); C23 made them keywords, and true/false now have type bool.
  • Converting to bool gives 1 for any non-zero value, unlike integer conversions, which truncate.
  • Comparisons and logical operators produce an int that is 0 or 1; library predicates like isdigit return any non-zero value.
  • Test flags with if (flag) / if (!flag), never == true; print them with %d or flag ? "true" : "false".
  • Watch for = vs ==, & vs &&, and chained comparisons like 0 < x < 10.

Next: Constants: const, #define, enum and constexpr, where you'll give fixed values meaningful names.