C语言 用 C 编写一个返回布尔值的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4752993/
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
Writing a function in C that returns a boolean
提问by olidev
As C does not have boolean types, how can I write a function like this in C:
由于 C 没有布尔类型,我如何在 C 中编写这样的函数:
bool checkNumber()
{
return false;
}
回答by templatetypedef
The booltype is defined in the <stdbool.h>header, and is available under the name _Boolotherwise (assuming you're using a C99 compiler). If you don't have C99, you can always invent your own bool type like this:
该bool类型在<stdbool.h>头文件中定义,并且在其他名称下可用_Bool(假设您使用的是 C99 编译器)。如果你没有 C99,你总是可以像这样发明你自己的 bool 类型:
typedef enum {false, true} bool;
回答by Fred Larson
intis commonly used as a Boolean in C, at least prior to C99. Zero means false, non-zero means true.
int通常在 C 中用作布尔值,至少在 C99 之前是这样。零表示假,非零表示真。
回答by jonescb
You could use defines to avoid using ints and 1s and 0s directly for boolean logic.
您可以使用定义来避免将整数和 1 和 0 直接用于布尔逻辑。
#define BOOL char
#define TRUE 1
#define FALSE 0
I chose char for BOOLbecause it's only 1 byte instead of 4. (For most systems)
我选择 charBOOL因为它只有 1 个字节而不是 4 个。(对于大多数系统)
回答by Keith
If you are not using C99, and determine that you need to add your own boolean type, then ensure that you give it its own name. Using 'bool' or 'BOOL' will only get you into trouble when you include a 3rd party library. The only exception would be to use the de-facto standard of:
如果您不使用 C99,并且确定需要添加自己的布尔类型,请确保为其指定名称。使用 'bool' 或 'BOOL' 只会在您包含 3rd 方库时给您带来麻烦。唯一的例外是使用以下事实标准:
#define BOOL int
#define TRUE 1
#define FALSE 0
But ensure you wrap these in #ifndef. But note that some libraries do use 'char' as BOOL. If you are coming from C++ background, have a think as to whether you will want to interoperate with C++.
但请确保将它们包装在#ifndef 中。但请注意,某些库确实使用“char”作为 BOOL。如果您来自 C++ 背景,请考虑是否要与 C++ 进行互操作。

