TIL Boolean variables don't exist in C

God please have mercy one me.

C99 has a _Bool data type, which is basically an integer that can be 0 or 1. If you #include <stdbool.h>, then you have bool defined, as well as true and false. It’s basically just a few #define preprocessor directives. A minimal example:

#include <stdbool.h>

int main() {
    bool myBool = true;

    if (myBool) {
        return 1;
    }
    else {
        return 0;
    }
}

However, any primitive data type can be a boolean in C. If it is 0, it is false, if it is anything else, it is true. Typically, int is used for that purpose, as in your screenshot.

Also, you don’t need to test for == 1 or == 0 (or == true or == false) in an if statement, as that is a tautology. So, it’s enough to put if (didYouSqueeze) if you test for true, or if (!didYouSqueeze) if you test for false.

4 Likes

You should use preprocessor. What could posibly go wrong? :grinning:

#define bool    int
#define true    1
#define false   0

I read somewhere that plain int is prefered because it should be the “fastest” data type (easiest to allocate, read and write) any platform can work with. Other types like char are then masked from int.
Not sure if it is true or not.

1 Like

But did you squeeze?

3 Likes

Oh yeahm i forgot about int

Yes Rico. Squeeze.