在C中使用布尔值
C没有任何内置布尔类型。在C中使用它们的最佳方法是什么?
C doesn't have any built-in Boolean types. What's the best way to use them in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
C没有任何内置布尔类型。在C中使用它们的最佳方法是什么?
C doesn't have any built-in Boolean types. What's the best way to use them in C?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(19)
从最好到更糟:
选项1(C99和更新)
选项2
选项3
选项4
说明
如果您不确定,请选择#1!
From best to worse:
Option 1 (C99 and newer)
Option 2
Option 3
Option 4
Explanation
If you are undecided, go with #1!
关于c的布尔人的一些想法:
我年纪大了,以至于我只使用普通的
int
作为我的布尔类型,而没有任何typedefs或特殊定义或枚举的true/false值。如果您在下面遵循我的建议,即永远不会与布尔常量进行比较,那么您只需要使用0/1即可初始化标志。但是,在这些现代时期,这种方法可能被认为太反动了。在这种情况下,绝对应该使用< stdbool.h>
,因为它至少具有标准化的好处。无论呼唤布尔常数如何,都只能将其用于初始化。永远不要写这样的东西
可以始终被更清晰的注释所取代
,即这些内容实际上可以合理,可以理解的是大声朗读。
给您的布尔变量阳性名称,即
完整
,而不是notfull
。后者导致很难轻松阅读的代码。与。
前一对自然读取,而
!notfull
也很尴尬,即使是它的读数也很尴尬,并且在更复杂的布尔表达式中变得更糟通常应该避免布尔论点。考虑一个在功能正文中定义的函数
,很明显该论点的含义是什么,因为它具有方便,有意义的名称。但是,呼叫站点看起来像是
在这里看起来不可能说出参数的含义,而不必总是查看函数定义或声明,并且如果您添加更多的布尔参数,则很快就会变得更糟。我建议
或
在任何一种情况下,呼叫网站现在看起来像
读者至少有机会理解的机会,而无需挖出
foo
的定义。A few thoughts on booleans in C:
I'm old enough that I just use plain
int
s as my boolean type without any typedefs or special defines or enums for true/false values. If you follow my suggestion below on never comparing against boolean constants, then you only need to use 0/1 to initialize the flags anyway. However, such an approach may be deemed too reactionary in these modern times. In that case, one should definitely use<stdbool.h>
since it at least has the benefit of being standardized.Whatever the boolean constants are called, use them only for initialization. Never ever write something like
These can always be replaced by the clearer
Note that these can actually reasonably and understandably be read out loud.
Give your boolean variables positive names, ie
full
instead ofnotfull
. The latter leads to code that is difficult to read easily. Comparewith
Both of the former pair read naturally, while
!notfull
is awkward to read even as it is, and becomes much worse in more complex boolean expressions.Boolean arguments should generally be avoided. Consider a function defined like this
Within the body of the function, it is very clear what the argument means since it has a convenient, and hopefully meaningful, name. But, the call sites look like
Here, it's essentially impossible to tell what the parameter meant without always looking at the function definition or declaration, and it gets much worse as soon if you add even more boolean parameters. I suggest either
or
In either case, the call site now looks like
which the reader has at least a chance of understanding without dredging up the definition of
foo
.C中的布尔值是一个整数:对于false而言为零,为true。
另请参阅, C,C ++,Objective-C,Awk 。
A boolean in C is an integer: zero for false and non-zero for true.
See also Boolean data type, section C, C++, Objective-C, AWK.
这是我使用的版本:
因为false只有一个值,但是逻辑true可以具有许多值,但是技术设置为true是编译器将用于false的相反的编译器。
这会解决某人编码某些内容的问题:
我认为我们都同意这不是一个好习惯,而是一次进行“ true =!false”的成本,我们消除了这个问题。
[编辑]最后我使用了:
避免名称与定义
true
和false
的其他方案相撞。但是这个概念保持不变。[编辑]显示整数转换为布尔值:
第一个(最正确)!将非零整数转换为0,然后将第二个整数转换为第二个(最左)!将0转换为
myFalse
值。我将把它作为练习,让读者转换零整数。[编辑]
当需要特定值时,即使默认值相同,我的样式是在需要特定值时使用枚举中的值设置。示例:因为false需要为零,所以我使用
false = 0,
而不是false,
[edit]
显示如何使用GCC编译时限制枚举的大小:
也就是说,如果有人这样做:
结构的大小将是4个字节而不是16个字节。
Here is the version that I used:
Because false only has one value, but a logical true could have many values, but technique sets true to be what the compiler will use for the opposite of false.
This takes care of the problem of someone coding something that would come down to this:
I think we would all agree that that is not a good practice, but for the one time cost of doing "true = !false" we eliminate that problem.
[EDIT] In the end I used:
to avoid name collision with other schemes that were defining
true
andfalse
. But the concept remains the same.[EDIT] To show conversion of integer to boolean:
The first (right most) ! converts the non-zero integer to a 0, then the second (left most) ! converts the 0 to a
myfalse
value. I will leave it as an exercise for the reader to convert a zero integer.[EDIT]
It is my style to use the explicit setting of a value in an enum when the specific value is required even if the default value would be the same. Example: Because false needs to be zero I use
false = 0,
rather thanfalse,
[EDIT]
Show how to limit the size of enum when compiling with gcc:
That is, if someone does:
the size of the structure will be 4 bytes rather than 16 bytes.
如果您使用的是C99编译器,则具有对布尔类型的内置支持:
http://en.wikipedia.org/wiki/boolean_data_type
If you are using a C99 compiler it has built-in support for bool types:
http://en.wikipedia.org/wiki/Boolean_data_type
第一件事首先。 C,IE ISO/IEC 9899的布尔类型为 19年。这比预期 c编程生涯的长度与业余/学术/专业部件的长度访问这个问题时结合在一起。我的确超过了1 - 2年。这意味着在此期间,普通读者对C的所有知识都学到了任何东西,C实际上具有布尔数据类型。
对于数据类型,
#include&lt; stdbool.h&gt;
,并使用true
, false 和bool
。或不包括它,然后使用_Bool
,1
和0
而不是。在该线程的其他答案中促进了各种危险的做法。我将解决他们:
这是不可以的,因为一个休闲的读者 - 在这19年内确实学习了C-希望
bool
是指实际bool
数据类型,并且行为类似,但事实并非如此!例如,使用C99
bool
/_bool
,b
将设置为false> false
iffa
为零,true
否则。 c11 6.3.1.2p1使用
typedef
到位,double double
将被胁迫到int
- 如果双重值不在int
的范围内,则行为是不确定的。自然,如果
true
和false
在enum
中声明。甚至更危险的是在声明的
,因为现在除1和0之外的所有值都是无效的,并且如果将这样的值分配给该类型的变量, 行为将是完全不确定的。
因此, iff ,您不能出于某些不明显的原因使用C99,对于布尔变量,您应该使用:
int
and values0
0 and code> 1 < /code> as-is ;并仔细地将域转换从任何其他值转换为这些值!!
bool
,true
和false
呢First things first. C, i.e. ISO/IEC 9899 has had a boolean type for 19 years now. That is way longer time than the expected length of the C programming career with amateur/academic/professional parts combined when visiting this question. Mine does surpass that by mere perhaps 1-2 years. It means that during the time that an average reader has learnt anything at all about C, C actually has had the boolean data type.
For the datatype,
#include <stdbool.h>
, and usetrue
,false
andbool
. Or do not include it, and use_Bool
,1
and0
instead.There are various dangerous practices promoted in the other answers to this thread. I will address them:
This is no-no, because a casual reader - who did learn C within those 19 years - would expect that
bool
refers to the actualbool
data type and would behave similarly, but it doesn't! For exampleWith C99
bool
/_Bool
,b
would be set tofalse
iffa
was zero, andtrue
otherwise. C11 6.3.1.2p1With the
typedef
in place, thedouble
would be coerced to anint
- if the value of the double isn't in the range forint
, the behaviour is undefined.Naturally the same applies to if
true
andfalse
were declared in anenum
.What is even more dangerous is declaring
because now all values besides 1 and 0 are invalid, and should such a value be assigned to a variable of that type, the behaviour would be wholly undefined.
Therefore iff you cannot use C99 for some inexplicable reason, for boolean variables you should use:
int
and values0
and1
as-is; and carefully do domain conversions from any other values to these with double negation!!
BOOL
,TRUE
andFALSE
!C有一个布尔类型: bool (至少在过去的10(!)年中)
包括stdbool.h,true/true/fals会按预期工作。
C has a boolean type: bool (at least for the last 10(!) years)
Include stdbool.h and true/false will work as expected.
在布尔操作中,对非零的任何内容都可以评估为true,因此您可以公正
并使用常数。
Anything nonzero is evaluated to true in boolean operations, so you could just
and use the constants.
这只是对其他答案的补充和一些澄清,如果您可以使用 c99 。
我的一些偏好:
_bool
或bool
?两者都很好,但是bool
看起来比关键字_bool
更好。bool
和_bool
的接受值是:false
或true
。分配0
或1
而不是false
或true
是有效的,但是很难读取和理解逻辑流程。来自标准的一些信息:
_bool
是不是unsigned int
,但是组 无符号整数类型的一部分。它足够大,可以保持值0
或1
。bool
true
和false
,但肯定不是一个好主意。这种能力被认为是过时的,将来将被删除。_bool
或bool
,如果 scalarar 值到0
或比较0
它将为0
,否则结果是1
:_bool x x = 9;
9
将分配给x
时,将转换为1
。_bool
是1个字节(8位),通常会试图尝试使用其他位,但不建议使用,因为给出的唯一保证是只有一个位用于存储数据,不像具有8位可用的类型char
。This is just a complement to other answers and some clarification, if you are allowed to use C99.
Some of my preferences:
_Bool
orbool
? Both are fine, butbool
looks better than the keyword_Bool
.bool
and_Bool
are:false
ortrue
. Assigning0
or1
instead offalse
ortrue
is valid, but is harder to read and understand the logic flow.Some information from the standard:
_Bool
is notunsigned int
, but is part of the group unsigned integer types. It is large enough to hold the values0
or1
.bool
true
andfalse
but sure is not a good idea. This ability is considered obsolescent and will be removed in future._Bool
orbool
, if the scalar value is equal to0
or compares to0
it will be0
, otherwise the result is1
:_Bool x = 9;
9
is converted to1
when assigned tox
._Bool
is 1 byte (8 bits), usually the programmer is tempted to try to use the other bits, but is not recommended, because the only guaranteed that is given is that only one bit is use to store data, not like typechar
that have 8 bits available.如今。
示例:
输出:
Nowadays C99 supports boolean types but you need to
#include <stdbool.h>
.Example:
Output:
由于 c23
bool
和_bool
和true
和false
是布尔类型。bool
/_bool
是一种可以保存值true
或false
的类型。 逻辑运算符!,
||
和&amp;&amp;
可以使用。标量型值可以隐式转换为
bool
。零值算术类型转换为false
,以及null
pointers或类型nullptr_t
。任何其他标量型值转换为true
。可以找到促进更高整数类型的规则在这里。宏
bool
,true
和false
来自&lt; stdbool.h&gt;
被“删除”(从中删除专门的标题),但是实现仍然可以定义此类预定义的宏以兼容,并且实现仍然可以使用宏来实现它们,如果完成此操作,则程序仍然可以不确定并重新定义它们。宏__ bool_true_false_are_defined
已弃用。另请参阅 https:> https:// SC22/wg14/www/docs/n2935.pdf 。
由于 c99
_bool
是A boolean type 可以保存值1
或0
。 逻辑运算符!,
||
和&amp;&amp;
可以使用。将标量类型转换为
_bool
,任何等于零的值都将转换为0
,其他值将转换为1
。可以找到促进更高整数类型的规则在这里。标准标题
&lt; stdbool.h&gt;
提供了一个便利宏,将bool
定义为_bool
的别名,宏 true 扩展到 integer -type(不是_bool
!!)常数1
,宏 false 扩展到 integer 常数0
和宏__ bool_true_false_are_are_defined
,该将扩展到整数常数1
。允许程序不确定并重新定义宏bool
,true
和false
。在C99之前,
您可以编写
typedef Enum {false,true} bool;
之类的东西。Since C23
bool
and_Bool
, andtrue
andfalse
are language keywords for boolean types.bool
/_Bool
is a type that can hold either the valuetrue
orfalse
. Logical operators!
,||
, and&&
can be used.A scalar-typed value can be implicitly converted to
bool
. Zero-valued arithmetic types convert tofalse
, as well asnull
pointers, or anything of typenullptr_t
. Any other scalar-type values convert totrue
. Rules for promotion to higher-rank integer types can be found here.The macros
bool
,true
, andfalse
from<stdbool.h>
are "removed" (from that header specifically), but an implementation can still define such predefined macros for compatibility, and implementations can still use macros to implement them, and if that is done, programs can still undefine and redefine them. The macro__bool_true_false_are_defined
is deprecated.See also https://open-std.org/JTC1/SC22/WG14/www/docs/n2935.pdf.
Since C99
_Bool
is a language keyword for a boolean type that can hold either the value1
or0
. Logical operators!
,||
, and&&
can be used.When converting scalar types to
_Bool
, any value that compares equal to zero is converted to0
, and other value is converted to1
. Rules for promotion to higher-rank integer types can be found here.The standard header
<stdbool.h>
provides a convenience macro that definesbool
as an alias to_Bool
, a macrotrue
that expands to the integer-type (not_Bool
!) constant1
, a macrofalse
that expands to the integer constant0
, and a macro__bool_true_false_are_defined
that expands to the integer constant1
. Programs are allowed to undefine and redefine the macrosbool
,true
, andfalse
.Prior to C99
You could write something like
typedef enum { false, true } bool;
.您可以使用_bool,但是返回值必须是整数(true 1,为false 0)。
但是,建议在C ++中包含并使用布尔,如所述
此答复来自 daniweb论坛,以及这个答案
You could use _Bool, but the return value must be an integer (1 for true, 0 for false).
However, It's recommended to include and use bool as in C++, as said in
this reply from daniweb forum, as well as this answer, from this other stackoverflow question:
如果条件表达式不为零,则认为它们是正确的,但是C标准要求逻辑运算符本身返回0或1。
@tom:#define true!false!false是不好的,完全毫无意义。如果标题文件进入编译的C ++代码,则可能导致问题:
某些编译器将对INT =&GT产生警告;布尔转换。有时人们会通过这样做避免这种情况:
迫使表达为C ++布尔。但是,如果您#define true!false,您最终会出现:
最终进行INT-to-bool比较,无论如何都会触发警告。
Conditional expressions are considered to be true if they are non-zero, but the C standard requires that logical operators themselves return either 0 or 1.
@Tom: #define TRUE !FALSE is bad and is completely pointless. If the header file makes its way into compiled C++ code, then it can lead to problems:
Some compilers will generate a warning about the int => bool conversion. Sometimes people avoid this by doing:
to force the expression to be a C++ bool. But if you #define TRUE !FALSE, you end up with:
which ends up doing an int-to-bool comparison that can trigger the warning anyway.
就是这样:
It is this:
您可以使用char或其他小型容器。
伪代码
You can use a char, or another small number container for it.
Pseudo-code
如果您使用的是C99,则可以使用
_Bool
类型。没有#include
是必要的。但是,您确实需要像整数一样对待它,其中1
是 true 和0
isfalse
。然后,您可以定义
true
和false
。If you are using C99 then you can use the
_Bool
type. No#include
s are necessary. You do need to treat it like an integer, though, where1
istrue
and0
isfalse
.You can then define
TRUE
andFALSE
.这就是我使用的:
_bool
是内置的类型。它是针对布尔值的。This is what I use:
_Bool
is a built in type in C. It's intended for boolean values.您可以简单地使用
#define
指令如下:并按如下:
等等:
You can simply use the
#define
directive as follows:And use as follows:
and so on