Using booleans in C


C99 standard. stdbool.h



C99 standard defined booleans in C, by using stdbool.h header.

This header defines:
  • bool type

  • true expands to 1

  • false expands to 0


If you set a bool variable to a value different from zero it is automatically assigned to one.


If you do use a former standard you can use an integer like a boolean: 0 equals false and other value equals true.

or use a trick:
typedef enum { false, true } bool;


Some guidelines to use booleans:


  • Do not compare against true, false, zero, etc:

  • e.g:
    bool foo;
    ...
    if (foo == true) (BAD)
    if (foo == 1) (BAD)
    if (foo) (GOOD)

    if (foo == false) (BAD)
    if (!foo) (GOOD)



  • Give positive names to boolean variables

  • It becames difficult to read.

    (BAD)
    bool not_done;
    if(!not_done)


    (GOOD)
    bool done;
    if (done)



  • Avoid booleans in function arguments.

  • It becames difficult to understand argument meaning in function calls.

    int foo(bool option);

    foo(true);


REFERENCE


stdbool.h
Using Booleans in C (Stack Overflow)