Thread: Best practice for true/false variables

  1. #1
    Registered User
    Join Date
    Aug 2018
    Posts
    19

    Best practice for true/false variables

    Every time I have a variable of which value will only be either 0 (false) or 1 (true) I use the int type. However, I decided to investigate a bit to see if there are more ways to do it. I would like to know which of the following methods is considered "more correct":
    • Just a plain int type.
    • An int type using bit fields:

    Code:
    int checked : 1;
    checked = 0;

    • A bool type variable using the stdbool.h library:

    Code:
    bool checked;
    checked = false

    I would also like to know if it is recommended to use the bool type. It is part of the C99 standard, so most compilers should allow it. Right?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    834
    You can only use a bit field inside a struct. And it would only make sense if you had multiple booleans to represent. It's really just for saving space.
    Code:
    #include <stdio.h>
     
    typedef struct Status {
        unsigned char a:1, b:1, c:1, d:1;
    } Status;
     
    int main() {
        Status st = {1,0,0,1};
        printf("value: %d%d%d%d\n", st.a, st.b, st.c, st.d); // prints 1001
        printf("bytes: %zu\n", sizeof st);                   // prints 1
    }
    Using an int for a boolean is okay, but it does mean that it's less clear that's what it is (although the name should be a big hint). To make it more clear, many people would do something like this:
    Code:
    enum BOOL { FALSE, TRUE };
    C99 added stdbool.h in order to standardize this useful practice, choosing the same identifiers as C++: bool, false, and true. So it is an excellent idea to use stdbool.h and all modern C compilers will "allow" it as long as you tell them that you want (at least) the C99 standard.
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 08-15-2018, 05:44 PM
  2. True or False
    By camel-man in forum C Programming
    Replies: 9
    Last Post: 02-14-2013, 01:27 AM
  3. true or false
    By johngav in forum C Programming
    Replies: 4
    Last Post: 03-19-2009, 02:25 PM
  4. True / False
    By goran00 in forum C Programming
    Replies: 13
    Last Post: 03-14-2008, 03:26 PM
  5. 1 or 0 == true or false?
    By Discolemonade in forum C++ Programming
    Replies: 4
    Last Post: 08-14-2005, 04:08 PM

Tags for this Thread