Home C Booleans tutorial in C

Booleans tutorial in C

In the C programming language, Booleans are a way to represent truth values, commonly used for conditional statements.

C does not have a native bool data type in the original C standard (C89), but it was introduced in C99 as part of the stdbool.h library.

Before C99, booleans were typically represented using integers, where 0 means false and any non-zero value means true.

1. Using Integers as Booleans (Pre-C99)

Before stdbool.h was introduced, integers were used to represent booleans.

#include <stdio.h>

int main() {
    int isTrue = 1; // Non-zero means true
    int isFalse = 0; // Zero means false

    if (isTrue) {
        printf("isTrue is true\n");
    }

    if (!isFalse) {
        printf("isFalse is false\n");
    }

    return 0;
}

Explanation:

  • isTrue is set to 1 (true), and isFalse is set to 0 (false).
  • if (isTrue) checks if isTrue is non-zero, which is treated as true.
  • if (!isFalse) checks if isFalse is zero, treated as false.

Output:

isTrue is true
isFalse is false

2. Including stdbool.h (C99 Standard)

The stdbool.h header was introduced in C99, providing a native boolean type bool along with true and false values.

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

int main() {
    bool isTrue = true;
    bool isFalse = false;

    if (isTrue) {
        printf("isTrue is true\n");
    }

    if (!isFalse) {
        printf("isFalse is false\n");
    }

    return 0;
}

Explanation:

  • bool is now a defined type, with true and false as predefined values in stdbool.h.
  • if (isTrue) and if (!isFalse) work similarly to the integer-based approach but are more readable.

Output:

isTrue is true
isFalse is false

3. Boolean Expressions in Conditions

Booleans are commonly used in conditions to evaluate expressions, where relational operators return boolean values.

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

int main() {
    int a = 5, b = 10;
    bool result = (a < b);

    if (result) {
        printf("a is less than b\n");
    } else {
        printf("a is not less than b\n");
    }

    return 0;
}

Explanation:

  • The expression (a < b) evaluates to true (1), which is assigned to result.
  • result is used in the if condition to print the correct message.

Output:

a is less than b

4. Using Boolean Variables in Functions

Boolean values are often used as return values in functions that need to confirm a condition.

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

bool isEven(int num) {
    return num % 2 == 0;
}

int main() {
    int num = 4;

    if (isEven(num)) {
        printf("%d is even\n", num);
    } else {
        printf("%d is odd\n", num);
    }

    return 0;
}

Explanation:

  • isEven is a function that returns true if num is even, otherwise false.
  • if (isEven(num)) uses the boolean result to check if num is even or odd.

Output:

4 is even

5. Combining Boolean Expressions with Logical Operators

Boolean values can be combined using logical operators: && (and), || (or), and ! (not).

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

int main() {
    int x = 5, y = 10;
    bool result = (x > 0) && (y > 0); // True if both x and y are positive

    if (result) {
        printf("Both x and y are positive\n");
    } else {
        printf("Either x or y is non-positive\n");
    }

    result = (x > 0) || (y < 0); // True if x is positive or y is negative
    if (result) {
        printf("Either x is positive or y is negative\n");
    }

    return 0;
}

Explanation:

  • (x > 0) && (y > 0) checks if both x and y are positive.
  • (x > 0) || (y < 0) checks if x is positive or y is negative.

Output:

Both x and y are positive
Either x is positive or y is negative

6. Negating Boolean Values with !

The ! operator negates a boolean value, converting true to false and vice versa.

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

int main() {
    bool isValid = false;

    if (!isValid) {
        printf("isValid is false\n");
    }

    isValid = !isValid; // Toggle isValid to true
    if (isValid) {
        printf("isValid is now true\n");
    }

    return 0;
}

Explanation:

  • !isValid negates isValid to evaluate the opposite of its value.
  • isValid = !isValid toggles isValid from false to true.

Output:

isValid is false
isValid is now true

7. Boolean Array

An array of booleans is useful for tracking the state of multiple items.

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

int main() {
    bool flags[3] = {true, false, true};

    for (int i = 0; i < 3; i++) {
        if (flags[i]) {
            printf("Flag %d is true\n", i);
        } else {
            printf("Flag %d is false\n", i);
        }
    }

    return 0;
}

Explanation:

  • flags is an array of bool values.
  • Each element is checked with if (flags[i]) to print its state.

Output:

Flag 0 is true
Flag 1 is false
Flag 2 is true

8. Using Boolean Return Values to Control Loops

Boolean functions can help control loops by breaking out of the loop based on certain conditions.

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

bool search(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return true; // Target found
        }
    }
    return false; // Target not found
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int target = 3;

    if (search(arr, 5, target)) {
        printf("Target %d found\n", target);
    } else {
        printf("Target %d not found\n", target);
    }

    return 0;
}

Explanation:

  • search returns true if target is found in arr, otherwise false.
  • The if (search(…)) condition uses the returned boolean to print the result.

Output:

Target 3 found

9. Boolean Constants and Macros

In cases where stdbool.h is unavailable, you can create boolean macros.

#include <stdio.h>

#define TRUE 1
#define FALSE 0

typedef int bool;

int main() {
    bool isReady = TRUE;

    if (isReady) {
        printf("isReady is true\n");
    }

    return 0;
}

Explanation:

  • TRUE and FALSE are defined as macros with values 1 and 0.
  • bool is defined as an alias for int to use TRUE and FALSE as booleans.

Output:

isReady is true

10. Summary Table of Boolean Use Cases

Use Case Description Example Code
Integer as boolean Uses 0 and non-zero values as false and true int isTrue = 1;
Using stdbool.h Introduces native bool, true, false types #include <stdbool.h>
Boolean expressions Assigns expressions to boolean variables bool result = (a < b);
Boolean functions Returns boolean value from function bool isEven(int num);
Logical operators Combines boolean expressions with &&, `
Negating values with ! Uses ! to toggle boolean value if (!isValid) …
Boolean array Array holding multiple boolean values bool flags[3] = {true, false, true};
Boolean-controlled loops Uses boolean return values to control loops bool search(int arr[], int size, int target);
Boolean macros (Pre-C99) Defines TRUE and FALSE as 1 and 0 #define TRUE 1 / #define FALSE 0

Complete Example: Checking for Prime Numbers with Booleans

This example demonstrates checking if numbers are prime using boolean functions and arrays.

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

bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int numbers[] = {2, 4, 5, 8, 11};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    for (int i = 0; i < size; i++) {
        if (isPrime(numbers[i])) {
            printf("%d is a prime number\n", numbers[i]);
        } else {
            printf("%d is not a prime number\n", numbers[i]);
        }
    }

    return 0;
}

Explanation:

  • isPrime checks if a number is prime and returns true or false.
  • The loop in main calls isPrime on each element in numbers and prints the result.

Output:

2 is a prime number
4 is not a prime number
5 is a prime number
8 is not a prime number
11 is a prime number

Booleans in C provide a way to manage conditions and logical operations. Although C initially lacked a dedicated boolean type, stdbool.h and common practices make working with boolean values straightforward.

You may also like