How to use the bool data type in C language?

In C language, there is no built-in bool type, but the int type can be used to simulate bool type. Typically, 0 is considered false, while any non-zero value is considered true.

For example, you can create a function to determine if a number is even.

#include <stdio.h>

int isEven(int num) {
    if (num % 2 == 0) {
        return 1;  // 返回非零值表示真(true)
    } else {
        return 0;  // 返回零值表示假(false)
    }
}

int main() {
    int num = 4;
    if (isEven(num)) {
        printf("%d is even\n", num);
    } else {
        printf("%d is odd\n", num);
    }
    return 0;
}

The output is:

4 is even

The introduction of the _Bool type and the stdbool.h header file in the C99 standard (or in C++) is to support the bool type. It can be used as follows:

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

int main() {
    _Bool b1 = true;  // 或者使用bool类型
    _Bool b2 = false;  // 或者使用bool类型

    if (b1) {
        printf("b1 is true\n");
    } else {
        printf("b1 is false\n");
    }

    if (b2) {
        printf("b2 is true\n");
    } else {
        printf("b2 is false\n");
    }

    return 0;
}

The output results are:

b1 is true
b2 is false
bannerAds