Thuta Learning
C
BasicProgrammingBeginner

Booleans

CLesson 1020 min

What you'll walk away with

  • Predict which values count as true and which as false in a condition
  • Use bool, true and false from <stdbool.h> and explain how C17 and C23 differ
  • Understand how storing a value in a bool normalises it to 0 or 1
  • Avoid == true, chained comparisons and using ~ where ! was meant

Explain it simply

Explain it simply

A boolean is the answer to a yes/no question: is the user logged in, is the item in stock, is the battery low? The earliest versions of C had no separate boolean type, so programmers used int, treating 0 as false and every other value as true. That rule still sits underneath every condition in C today.

Since C99, including <stdbool.h> gives you the names bool, true and false, which make code easier to read. bool isPaid = true; tells the reader at once that the variable only ever holds a yes or a no.

Problem → Why → Solution

The problem: a "not found" -1 that counts as true

Imagine search code that gives a name's index (0, 1, 2...) when found and -1 when not. The developer assumes "found means true" and writes if (position). When the name is missing, the program announces Found at index -1, and when the name really is at index 0 it shows nothing. The logic is backwards in both directions.

lookup.c
int position = -1;            /* -1 means "name not found" */

if (position) {               /* -1 is nonzero, so this is true */
  printf("Found at index %d\n", position);
}

position = 0;                 /* found at the very first index */
if (position) {               /* 0 is false: the real hit is ignored */
  printf("Found at index %d\n", position);
}

Why does the logic flip?

In a condition, C asks exactly one question: is this value zero? -1 is not zero, so it is true, and index 0 is zero, so it is false. C has no idea what a value means to your program. Write a comparison that says what you mean, such as if (position >= 0).

Core concept: C's rules of truth

A condition in C accepts any scalar value. 0, 0.0 and a null pointer are false; everything else, whether 1, -1, 42 or 0.5, is true. In the other direction, comparison operators (== < >= ...) and logical operators (&& || !) always produce exactly the int 1 or 0, never a value such as 2 or -1.

C99 added the type _Bool, which can hold only 0 and 1. <stdbool.h> provides macros: bool as a name for _Bool, true as 1 and false as 0. Storing any value in a bool turns every nonzero value into 1: bool b = 5; gives 1, and so does bool b = 0.5; (whereas storing 0.5 in an int gives 0). That normalisation makes bool safer than a plain int.

In C23, bool, true and false became keywords of the language, so the header is no longer required there. Including it is still harmless and keeps the code working with C99, C11 and C17 compilers. Recent GCC versions default to C23, so code may compile without the header, but with gcc -std=c17 it fails with error: unknown type name 'bool'. Keep the include.

printf has no specifier for bool. A bool is promoted to int, so %d prints 1 or 0; for words, use condition ? "true" : "false". Finally, keep logical operators (! && ||), which work on truth, apart from bitwise operators (~ & |), which work on bits: !1 is 0, but ~1 is -2, which is still true.

When you combine bools with && and ||, use the short-circuit rule that stops as soon as the answer is known. In isLoggedIn && hasPermission, nobody's permission is consulted until someone is logged in. Put the protective or cheapest test on the left.

Mental model: the only question C asks
  1. Take the value in the condition
  2. Ask: is it zero?
  3. Zero is false; anything else is true
  4. Stored in a bool, it becomes 0 or 1

C does not know what a value means (an error, not found, a count), so spell out your intent with a comparison.

General pattern

c
#include <stdbool.h>          /* bool, true, false (built in since C23) */

bool flagName = true;          /* or false */
bool fromTest = value > limit; /* a comparison gives 1 or 0 */
bool combined = flagA && !flagB;

printf("%d\n", flagName);                      /* prints 1 or 0 */
printf("%s\n", flagName ? "true" : "false");   /* prints a word */

A bool can be set directly to true or false, or to the result of a comparison or logical expression. %d prints 1 or 0, and ? : picks one of two words.

Example: login and permission flags

This program stores a user's login and permission state in bools and combines them with && and !. The later lines show what happens when an int is stored in a bool, and what value a comparison produces.

booleans.c
#include <stdio.h>
#include <stdbool.h>

int main(void) {
  bool isLoggedIn = true;
  bool hasPermission = false;
  bool canEdit = isLoggedIn && hasPermission;

  printf("Logged in: %d\n", isLoggedIn);
  printf("Permission: %d\n", hasPermission);
  printf("Can edit: %d\n", canEdit);
  printf("Not logged in: %d\n", !isLoggedIn);

  int unread = 5;
  bool hasUnread = unread;
  printf("unread = %d, hasUnread = %d\n", unread, hasUnread);
  printf("Is 7 > 3? %d\n", 7 > 3);
  return 0;
}

Code breakdown

  1. Line 2#include <stdbool.h>

    Up to C17, this header supplies the names bool, true and false. Remove it and compile with -std=c17, and you get unknown type name 'bool'.

  2. Line 7bool canEdit = isLoggedIn && hasPermission;

    The user is logged in but lacks permission, so the && gives 0. Storing a rule in a well-named bool makes later conditions easy to read.

  3. Lines 9-12printf("Not logged in: %d\n", !isLoggedIn);

    Printed with %d, the bools show as 1 and 0. ! turns true into 0 and false into 1.

  4. Lines 14-15bool hasUnread = unread;

    unread is 5, but stored in a bool it becomes 1: every nonzero value is true, and a bool normalises it to 1. unread itself is still 5.

  5. Line 177 > 3

    A comparison's result is the int 1 or 0, not a bool. Here 7 > 3 is true, so it is 1.

You should see
Logged in: 1
Permission: 0
Can edit: 0
Not logged in: 0
unread = 5, hasUnread = 1
Is 7 > 3? 1

Printing bools as words, and normalising

condition ? A : B (the conditional operator) gives A when the condition is true and B otherwise; the if...else lesson covers it again. Combined with %s in printf, it shows a bool as a word like "yes" or "no". The program below also contrasts storing 0.5 in a bool with storing it in an int, and shows the !! idiom that turns any int into 0 or 1.

bool_words.c
#include <stdio.h>
#include <stdbool.h>

int main(void) {
  int battery = 15;
  bool lowBattery = battery < 20;
  bool charging = false;

  printf("Low battery: %s\n", lowBattery ? "yes" : "no");
  printf("Show warning: %s\n", (lowBattery && !charging) ? "true" : "false");

  double ratio = 0.5;
  bool fromDouble = ratio;      /* any nonzero value becomes true (1) */
  int asInt = (int)ratio;       /* conversion to int truncates to 0 */
  printf("bool from 0.5 = %d, int from 0.5 = %d\n", fromDouble, asInt);
  printf("!!42 = %d\n", !!42);
  return 0;
}

In real projects

Where this shows up in real projects

Modern C code uses bool for option flags (verbose, dry_run), for the return value of validation functions such as is_valid_email(), and for state such as is_connected. Most of the standard library and system APIs predate bool, though, and return an int with its own meaning. strcmp(a, b) returns 0 when the strings are equal, so if (strcmp(a, b)) means "if different", not "if equal". main returns 0 for success, and many POSIX functions return -1 on error.

That is why experienced C programmers read the documentation before putting an int-returning function in a condition, and then write an explicit comparison such as if (strcmp(a, b) == 0) or if (result == -1). Bit flags need the same care: flags & CAN_WRITE can yield a value like 4 rather than 1, so it is normalised by storing it in a bool or comparing with != 0.

Common mistakes

Common mistakes

1. Comparing an int with true

true is just 1, so with int count = 5;, count == true is 0 (false) even though count is nonzero and therefore "true". Write if (count) or if (count != 0); even for bools, == true adds nothing.

2. Chaining comparisons like in maths

if (0 < t < 10) is evaluated as (0 < t) < 10. 0 < t is only ever 0 or 1, which is always below 10, so it is true even for t = 50. GCC warns comparisons like 'X<=Y<=Z' do not have their mathematical meaning. Write 0 < t && t < 10.

3. Using ~ where ! was meant

~ flips every bit, so ~1 is -2, which is true; if (~isReady) runs even when isReady is true. GCC's -Wall warns '~' on a boolean expression and asks did you mean to use logical not? Use ! for logical NOT.

Best practices

Best practices

  • Use bool, not int, for a value that only ever holds yes or no.
  • Start bool names with is, has or can (isPaid, hasAccess, canRetry) so that if (isPaid) reads like a sentence.
  • When an int such as a count, an index or an error code goes into a condition, write the comparison out: > 0, >= 0, == -1.
  • Keep #include <stdbool.h> so the code also builds with C17 and older compilers.

Mini challenge

Mini challenge: an entry checker

Write an entry checker for an event: a visitor needs a ticket, and must be 18 or older or come with an adult. Also handle a database lookup result of -1 ("not found") correctly.

  • Use age = 17, hasTicket = true, withAdult = true and lookupResult = -1
  • Compute three bools, isAdult, canEnter and found, with comparison and logical operators
  • Compare lookupResult with >= 0 instead of using it directly as a condition
  • Print canEnter and found as yes/no, and "needs ID check" (not an adult but allowed in) as 1/0
entry_check.c
#include <stdio.h>
#include <stdbool.h>

int main(void) {
  int age = 17;
  bool hasTicket = true;
  bool withAdult = true;
  int lookupResult = -1;              /* -1 means "not found" */

  /* TODO: bool isAdult = ... */
  /* TODO: bool canEnter = ticket AND (adult OR with an adult) */
  /* TODO: bool found = ... (do not use lookupResult on its own) */

  /* TODO: print isAdult as 1/0, canEnter and found as yes/no */
  /* TODO: print whether an ID check is needed (1/0) */
  return 0;
}

Expected: The program prints these four lines: Adult: 0 Can enter: yes Record found: no Needs ID check: 1

Show hint

Put the || part of canEnter in parentheses, because && binds tighter than ||. To print a word, use printf("%s\n", flag ? "yes" : "no");.

Show solution
entry_check.c
#include <stdio.h>
#include <stdbool.h>

int main(void) {
  int age = 17;
  bool hasTicket = true;
  bool withAdult = true;
  int lookupResult = -1;              /* -1 means "not found" */

  bool isAdult = age >= 18;
  bool canEnter = hasTicket && (isAdult || withAdult);
  bool found = lookupResult >= 0;

  printf("Adult: %d\n", isAdult);
  printf("Can enter: %s\n", canEnter ? "yes" : "no");
  printf("Record found: %s\n", found ? "yes" : "no");
  printf("Needs ID check: %d\n", !isAdult && canEnter);
  return 0;
}

Quick quiz 1 / 3

Given int count = 5;, what does printf("%d\n", count == true); print?

Quick quiz 2 / 3

Compiling with gcc -std=c17, which line only compiles if <stdbool.h> is included?

Quick quiz 3 / 3

What does bool b = 0.5; printf("%d\n", b); print?

What to remember

  • In a condition, zero is false and every other value, including -1, is true.
  • Comparison and logical operators produce exactly the int 1 or 0.
  • <stdbool.h> provides bool, true and false; C23 makes them keywords, but the include stays harmless.
  • Any value stored in a bool becomes 0 or 1; do not use == true or ~ for logical tests.
  • Write error codes and indexes in conditions as comparisons such as >= 0 or == -1.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Booleans | Thuta Learning