How to use boolean datatype in C?

后端 未结 7 595
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 13:59

I was just writing code in C and it turns out it doesn\'t have a boolean/bool datatype. Is there any C library which I can include to give me the ability to return a boolean

相关标签:
7条回答
  • 2020-12-23 14:16

    As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races

    0 讨论(0)
  • 2020-12-23 14:23

    C99 has a bool type. To use it,

    #include <stdbool.h>
    
    0 讨论(0)
  • 2020-12-23 14:24

    If you have a compiler that supports C99 you can

    #include <stdbool.h>
    

    Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:

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

    In my opinion, though, you may as well just use int and use zero to mean false and nonzero to mean true. That's how it's usually done in C.

    0 讨论(0)
  • 2020-12-23 14:25

    We can use enum type for this.We don't require a library. For example

               enum {false,true};
    

    the value for false will be 0 and the value for true will be 1.

    0 讨论(0)
  • 2020-12-23 14:26
    struct Bool {
        int true;
        int false;
    }
    
    int main() {
    
        /* bool is a variable of data type – bool*/
        struct Bool bool;
    
        /*below I’m accessing struct members through variable –bool*/ 
        bool = {1,0};
        print("Student Name is: %s", bool.true);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-23 14:28

    C99 introduced _Bool as intrinsic pure boolean type. No #includes needed:

    int main(void)
    {
      _Bool b = 1;
      b = 0;
    }
    

    On a true C99 (or higher) compliant C compiler the above code should compile perfectly fine.

    0 讨论(0)
提交回复
热议问题