[英]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
? 人们使用
int
或char
- 虽然看起来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
作为别名,如果你需要它(对于true
和false
也有#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
中的true
和false
也是整数。 If you want to spare memory - use bit-fields. 如果你想节省内存 - 使用位字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.