据我所知,有三种方法可以在c中使用布尔值
#define FALSE 0 ... #define TRUE !(FALSE)
我错过了其他方法吗?不同方法的优缺点是什么?
我想最快的是3号,2号更容易读取(尽管按位否定会略微增加开销),1是最易读的,与所有编译器不兼容.
已经阅读了这个相关的问题,但正在寻找一些更具体的东西.
int
-sized值传递?这是迄今为止我所包含的所有.h文件,但没有定义bool
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <event.h>
Run Code Online (Sandbox Code Playgroud)
哪个文件定义了bool
?
由于C没有bool
s,true
在使用的算法中代替什么是适当的变量
do
{
// ...
} while(true);
Run Code Online (Sandbox Code Playgroud)
???
一个合适的C程序员应该这样做
do
{
// ...
} while(1);
Run Code Online (Sandbox Code Playgroud)
或者是否有一个特定的变量保留意味着" 不是零/空 "的东西?
鉴于这x
是一个int
以数字5
作为其值的类型变量,请考虑以下语句:
int y = !!x;
Run Code Online (Sandbox Code Playgroud)
这就是我认为它发生的事情:x
隐式地转换为a bool
并且执行第一个否定,之后进行最后的否定,所以一个演员和两个否定.
我的问题是,不仅仅是使用bool(执行int y = (bool)x;
代替int y = !!x
)而不是使用双重否定,因为你正在执行两个否定.
我可能错了,因为我在Linux内核中看到了很多双重否定,但我不明白我的直觉出错了,也许你可以帮助我.
我提到了这个问题,其中一些答案表明这bool
是一个整体类型(IDE也将其视为关键字).
但是,没有一个答案表明cplusplus中提供的信息,它表示这bool
是一个通过添加的宏<cstdbool>
(在这种情况下,编译器可能在编译时允许隐式添加此头bool
).这是g ++版本的<stdbool.h>
.
究竟bool
是什么呢?一个整数类型的关键字或宏?
每当我需要布尔类型时,我被告知创建一个或更好的使用stdbool.h
.
自stdbool.h
使用以来typedef bool _Bool
,是否有理由使用标题而不仅仅使用类型_Bool
?它只是为了额外的宏(/* #define true 1 #define false 0 */
)吗?
编写返回表示状态代码的int的C或C++函数的最佳实践是什么?
具体来说,我想了解客户端使用情况,但欢迎其他提示.
例如,我可以写这样的东西:
int foo() {
return 0; // because everything was cool
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它?
if (foo()) {
// what to do if false, e.g. non-zero, e.g. not OK
} else {
// what to do if true, e.g. zero, e.g. OK
}
Run Code Online (Sandbox Code Playgroud)
这应该有效,因为最佳实践通常要求状态代码0
表示一切正常,也0
意味着false
在布尔语句中.
但是,这不会很好,对:
if (!foo()) {
// what to do if true
} else {
// what to do if false
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用返回类型作为boolean创建一个函数...程序的语法似乎是正确的但编译器给出错误....
我包含的头文件是:
#include<stdio.h>
#include<stdlib.h>
Run Code Online (Sandbox Code Playgroud)
我创建的功能是:
34.bool checknull(struct node* node){
35. if ( node != NULL )
36. return TRUE;
37.
38. return false;
39.}
Run Code Online (Sandbox Code Playgroud)
我在编译时得到的是
bininsertion.c:34:1: error: unknown type name ‘bool’
bininsertion.c: In function ‘checknull’:
bininsertion.c:36:10: error: ‘TRUE’ undeclared (first use in this function)
bininsertion.c:36:10: note: each undeclared identifier is reported only once for each function it appears in
bininsertion.c:38:9: error: ‘false’ undeclared (first use in this function)
Run Code Online (Sandbox Code Playgroud)
我用小写和大写字母都试过"真,假",但似乎没有用......