C没有任何内置布尔类型。在C语言中使用它们的最佳方式是什么?


当前回答

这就是:

#define TRUE 1
#define FALSE 0

其他回答

这就是:

#define TRUE 1
#define FALSE 0

现在C99支持布尔类型,但需要#include<stdbool.h>。

例子:

#include <stdbool.h>

int main() 
{ 
    bool arr[2] = {true, false}; 

    printf("%d\n", arr[0] && arr[1]);
    printf("%d\n", arr[0] || arr[1]);

    return 0; 
} 

输出:

0
1

您可以使用一个字符或另一个小数字容器。

伪码

#define TRUE  1
#define FALSE 0

char bValue = TRUE;

如果您使用的是C99编译器,它内置了对布尔类型的支持:

#include <stdbool.h>
int main()
{
  bool b = false;
  b = true;
}

http://en.wikipedia.org/wiki/Boolean_data_type

您可以简单地使用#define指令,如下所示:

#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;

使用方法如下:

bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);

等等