C语言 如何在 C 中使用布尔数据类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4159713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:59:48  来源:igfitidea点击:

How to use boolean datatype in C?

ctypesboolean

提问by itsaboutcode

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/bool datatype?

我只是用 C 编写代码,结果发现它没有 boolean/bool 数据类型。有没有我可以包含的 C 库来让我能够返回布尔/布尔数据类型?

回答by James McNellis

If you have a compiler that supports C99 you can

如果你有一个支持 C99 的编译器,你可以

#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:

否则,您可以根据需要定义自己的。根据您希望如何使用它(以及您是否希望能够将代码编译为 C++),您的实现可能非常简单:

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

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

不过,在我看来,您也可以int使用零来表示假,使用非零来表示真。这就是通常在 C 中完成的方式。

回答by caveman

C99 has a boolean datatype, actually, but if you must use older versions, just define a type:

C99 实际上有一个布尔数据类型,但如果你必须使用旧版本,只需定义一个类型:

typedef enum {false=0, true=1} bool;

回答by kavya

C99 has a booltype. To use it,

C99 有一个bool类型。要使用它,

#include <stdbool.h>

回答by ysap

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

作为 James McNellis 答案的替代方案,我总是尝试对 bool 类型使用枚举而不是宏:typedef enum bool {false=0; true=1;} bool;。b/c 更安全,它让编译器进行类型检查并消除宏扩展竞争

回答by alk

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

C99_Bool作为内部纯布尔类型引入。不需要#include

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

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

在真正符合 C99(或更高版本)的 C 编译器上,上述代码应该可以完美编译。

回答by Sri Charan

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

我们可以为此使用枚举类型。我们不需要库。例如

           enum {false,true};

the value for falsewill be 0 and the value for truewill be 1.

for 的值为false0,for 的值为true1。

回答by M.zar

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;
}