简体   繁体   English

Char或Int表示C中的布尔值?

[英]Char or Int for boolean value in C?

I find that there is no native bool type. 我发现没有原生bool类型。 People either use int or char - though it seem that int might be more frequently used than char ? 人们使用intchar - 虽然看起来int可能比char更频繁使用? Is this true? 这是真的?

My first impulse was to use char as it is a smaller data type, but there something I've missed? 我的第一个冲动是使用char因为它是一个较小的数据类型,但有一些我错过了? Is int better for boolean values, and if so - why? 对于布尔值, int更好吗?如果是,为什么?

There is a _Bool in C99 , and a bool if you include stdbool.h . C99中有一个_Bool ,如果包含stdbool.h则有一个bool

If you don't have it (a decently modern compiler), use int , it's usually the fastest type. 如果你没有它(一个相当现代的编译器),使用int ,它通常是最快的类型。 The memory savings of using char are likely negligible. 使用char节省的内存可能微不足道。

If you're using a reasonably modern C compiler then you just need: 如果你正在使用一个相当现代的C编译器,那么你只需要:

#include <stdbool.h>

This typically has a macro such as: 这通常有一个宏,如:

#define bool _Bool

which lets you use C99's built-in _Bool type wherever you need a bool . 这使您可以在任何需要bool地方使用C99的内置_Bool类型。

There is a native type named _Bool (starting with C99). 有一个名为_Bool的本机类型(从C99开始)。 In <stdbool.h> , there's also a #define to provide bool as an alias, if you want it (also has #define s for true and false ). <stdbool.h> ,还有一个#define来提供bool作为别名,如果你需要它(对于truefalse也有#define )。

According to ISO-9899 the result of relation, logical and equality operators has type int . 根据ISO-9899 ,关系结果,逻辑和相等运算符的类型为int true and false from stdbool.h are also integers. stdbool.h中的truefalse也是整数。 If you want to spare memory - use bit-fields. 如果你想节省内存 - 使用位字段。

Actually there's no real difference since char gets always promoted to int when using it (check this ). 实际上没有真正的区别,因为char在使用时总是被提升为int(检查这个 )。 I have never seen a char used as a bool though, so I'd go for using an int. 我从来没有见过用作bool的char,所以我会去使用int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM