C bool & Boolean Types

Working with boolean values in C programming

✅ What are Boolean Types?

Boolean types represent true/false values in C. Since C99, the _Bool type and stdbool.h header provide standardized boolean support with true and false constants.


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

int main() {
    bool is_ready = true;
    bool is_done = false;
    
    printf("Ready: %s\n", is_ready ? "Yes" : "No");
    return 0;
}
                                    

Boolean Concepts

🔢

_Bool Type

Native boolean type since C99

_Bool flag = 1;
📚

stdbool.h

Standard boolean definitions

#include <stdbool.h>

true/false

Boolean constants

bool x = true;
bool y = false;
🔄

bool Macro

Convenient bool alias

bool is_valid = true;

🔹 Basic Boolean Usage

bool data type represents true or false values, enabling clearer logical programming. Include <stdbool.h> to use standard booleans in C programs. Boolean variables improve code readability by explicitly representing logical states instead of using integers. Functions returning bool make intent obvious to programmers reading the code. Booleans integrate seamlessly with conditional statements, loops, and logical operations for expressive programming logic.

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

int main() {
    // Boolean declarations
    bool is_active = true;
    bool is_complete = false;
    _Bool native_bool = 1;
    
    // Boolean operations
    bool result1 = is_active && is_complete;  // AND
    bool result2 = is_active || is_complete;  // OR
    bool result3 = !is_active;                // NOT
    
    printf("is_active: %s\n", is_active ? "true" : "false");
    printf("is_complete: %s\n", is_complete ? "true" : "false");
    printf("AND result: %s\n", result1 ? "true" : "false");
    printf("OR result: %s\n", result2 ? "true" : "false");
    printf("NOT result: %s\n", result3 ? "true" : "false");
    
    // Size of boolean
    printf("Size of bool: %zu bytes\n", sizeof(bool));
    printf("Size of _Bool: %zu bytes\n", sizeof(_Bool));
    
    return 0;
}

Output:

is_active: true
is_complete: false
AND result: false
OR result: true
NOT result: false
Size of bool: 1 bytes
Size of _Bool: 1 bytes

🔹 Boolean Conversion

Non-boolean values automatically convert to boolean following specific conversion rules. Zero converts to false; any non-zero value converts to true. Pointers convert similarly: NULL becomes false, non-NULL becomes true. This implicit conversion enables flexible programming patterns but requires careful attention to avoid bugs. Understanding conversion rules prevents logical errors when comparing different types. Explicit casting clarifies intent and improves code maintainability significantly.

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

void print_bool(const char* name, bool value) {
    printf("%s: %s\n", name, value ? "true" : "false");
}

int main() {
    // Integer to boolean conversion
    bool from_zero = 0;        // false
    bool from_nonzero = 42;    // true
    bool from_negative = -1;   // true
    
    // Pointer to boolean conversion
    int x = 10;
    bool from_valid_ptr = &x  // true (non-null pointer)
    bool from_null_ptr = NULL; // false (null pointer)
    
    // Float to boolean conversion
    bool from_zero_float = 0.0;   // false
    bool from_nonzero_float = 3.14; // true
    
    print_bool("from_zero", from_zero);
    print_bool("from_nonzero", from_nonzero);
    print_bool("from_negative", from_negative);
    print_bool("from_valid_ptr", from_valid_ptr);
    print_bool("from_null_ptr", from_null_ptr);
    print_bool("from_zero_float", from_zero_float);
    print_bool("from_nonzero_float", from_nonzero_float);
    
    return 0;
}

Output:

from_zero: false
from_nonzero: true
from_negative: true
from_valid_ptr: true
from_null_ptr: false
from_zero_float: false
from_nonzero_float: true

🔹 Boolean Functions

Create functions returning boolean values to represent yes/no, valid/invalid conditions clearly. Boolean return types make function purposes immediately obvious and code self-documenting. Examples include validation functions, comparison operations, and status checks. These functions integrate naturally with conditionals and logical operations. Returning true or false from functions creates intuitive APIs that developers understand instantly without studying documentation.

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

// Function returning boolean
bool is_even(int number) {
    return number % 2 == 0;
}

// Function taking boolean parameter
void print_status(bool enabled) {
    if (enabled) {
        printf("Status: ENABLED\n");
    } else {
        printf("Status: DISABLED\n");
    }
}

// Boolean validation function
bool is_valid_age(int age) {
    return age >= 0 && age <= 150;
}

// Boolean array processing
bool all_positive(int arr[], size_t size) {
    for (size_t i = 0; i < size; i++) {
        if (arr[i] <= 0) {
            return false;
        }
    }
    return true;
}

int main() {
    // Test boolean functions
    int numbers[] = {2, 4, 6, 8, 10};
    int mixed[] = {1, -2, 3, 4};
    
    printf("Is 8 even? %s\n", is_even(8) ? "Yes" : "No");
    printf("Is 7 even? %s\n", is_even(7) ? "Yes" : "No");
    
    print_status(true);
    print_status(false);
    
    printf("Is age 25 valid? %s\n", is_valid_age(25) ? "Yes" : "No");
    printf("Is age -5 valid? %s\n", is_valid_age(-5) ? "Yes" : "No");
    
    printf("All numbers positive? %s\n", 
           all_positive(numbers, 5) ? "Yes" : "No");
    printf("All mixed positive? %s\n", 
           all_positive(mixed, 4) ? "Yes" : "No");
    
    return 0;
}

Output:

Is 8 even? Yes
Is 7 even? No
Status: ENABLED
Status: DISABLED
Is age 25 valid? Yes
Is age -5 valid? No
All numbers positive? Yes
All mixed positive? No

🔹 Boolean Arrays and Structures

Use boolean arrays and structures to represent collections of logical states efficiently. Boolean arrays track multiple yes/no conditions, like presence flags or completion status. Structures containing boolean members organize related logical information cohesively. This approach improves code clarity by grouping related boolean data. Boolean fields consume minimal memory in structures, making them ideal for resource-constrained applications and large-scale data processing scenarios.

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

// Structure with boolean fields
struct User {
    char name[50];
    bool is_active;
    bool is_admin;
    bool email_verified;
};

// Boolean array for flags
typedef struct {
    bool flags[8];
    int count;
} FlagSet;

void print_user(struct User* user) {
    printf("User: %s\n", user->name);
    printf("  Active: %s\n", user->is_active ? "Yes" : "No");
    printf("  Admin: %s\n", user->is_admin ? "Yes" : "No");
    printf("  Email Verified: %s\n", user->email_verified ? "Yes" : "No");
}

void set_flag(FlagSet* fs, int index, bool value) {
    if (index >= 0 && index < 8) {
        fs->flags[index] = value;
        if (value) fs->count++;
        else fs->count--;
    }
}

int main() {
    // Create user with boolean properties
    struct User user1 = {
        .name = "Alice",
        .is_active = true,
        .is_admin = false,
        .email_verified = true
    };
    
    struct User user2 = {
        .name = "Bob",
        .is_active = false,
        .is_admin = true,
        .email_verified = false
    };
    
    print_user(&user1);
    printf("\n");
    print_user(&user2);
    printf("\n");
    
    // Boolean flag set
    FlagSet flags = {0};
    set_flag(&flags, 0, true);
    set_flag(&flags, 3, true);
    set_flag(&flags, 7, true);
    
    printf("Flag status:\n");
    for (int i = 0; i < 8; i++) {
        printf("Flag %d: %s\n", i, flags.flags[i] ? "SET" : "CLEAR");
    }
    printf("Total flags set: %d\n", flags.count);
    
    return 0;
}

Output:

User: Alice
  Active: Yes
  Admin: No
  Email Verified: Yes

User: Bob
  Active: No
  Admin: Yes
  Email Verified: No

Flag status:
Flag 0: SET
Flag 1: CLEAR
Flag 2: CLEAR
Flag 3: SET
Flag 4: CLEAR
Flag 5: CLEAR
Flag 6: CLEAR
Flag 7: SET
Total flags set: 3

🧠 Test Your Knowledge

Which header file provides the bool type and true/false constants?