Search code examples
c++cbooleanprimitive

Boolean data type vs integer data types to represent truth values


What is advantage of using bool data type over integer values as 0 and 1 for true and false values, which will be more efficient to use? And how it will differ in different languages like c and c++?


Solution

  • int was used in C when there was no bool, there is no advantage1 using an integer type to represent a boolean value in C++ or in modern C:

    1. bool is meaningful, int is not:
    bool try_something();
    int try_something(); // What does this return?
    

    It is common in C to have functioning returning int to indicate success or failure, but a lot (most?) of these do not return 1 on success and 0 on failure, they follow UNIX standard which is to return 0 in case of success and something else in case of error, so you get code like this:

    int close(int fd);
    
    if (close(fd)) { /* Something bad happened... */ }
    

    See close manual which returns 0 on success and -1 on failure. For new user, this code is disconcerting, you expect close to return something that is true if it succeed, not the opposite.

    1. If you need to store large amount of boolean values, you may want to optimize the storage by using only one bit to represent the value (against 32 bits if you store it in a int), and in C++, std::vector<bool>2 is already specialized to do that, so:
    std::vector<bool> bvec(8000); // Size ~ 1000 bytes (optimization of std::vector<bool>)
    std::vector<int> ivec(8000);  // Size ~ 32000 bytes (32-bits int)
    

    1 There are no advantages if you use them in the same way (e.g. by doing bool b = f(); vs. int b = f(); or the vector<bool> above (if you can replace int by bool without problem in your code, then do so)), but if you use an int to store multiple boolean values using bitwise operations, this is another question.

    2 Note that this only applies to std::vector<bool>, other containers such as std::array<bool, N> are not optimized because they cannot use proxy object to "represent" a bit value.