在C中1和0总是必须为真或假吗?

  • 本文关键字: c boolean
  • 更新时间 :
  • 英文 :


最近我发现了一些对我来说很有趣的代码,但是我不能很好地理解它,所以有人能给我解释一下吗?

这是康威的人生游戏。我认为这行可以像一个问题1代表真0代表假;对吗?但是为什么没有bool呢?

void iterGen(int WIDTH, int HEIGHT, char curMap[WIDTH][HEIGHT])
{
int i, j;
char tempMap[WIDTH][HEIGHT];
for (i = 0; i < WIDTH; i++)
{
for (j = 0; j < HEIGHT; j++)
{
int neighbors = 0;
neighbors += curMap[i+1][j+1] == '*' ? 1 : 0;
neighbors += curMap[i+1][j] == '*' ? 1 : 0;
neighbors += curMap[i+1][j-1] == '*' ? 1 : 0;
neighbors += curMap[i][j+1] == '*' ? 1 : 0;
neighbors += curMap[i][j-1] == '*' ? 1 : 0;
neighbors += curMap[i-1][j+1] == '*' ? 1 : 0;
neighbors += curMap[i-1][j] == '*' ? 1 : 0;
neighbors += curMap[i-1][j-1] == '*' ? 1 : 0;
if (curMap[i][j] == ' ')
{
tempMap[i][j] = neighbors == 3 ? '*' : ' ';
}
else if (curMap[i][j] == '*')
{
tempMap[i][j] = neighbors < 2 || neighbors > 3 ? ' ' : '*';
}
}
}
for (i = 0; i < WIDTH; i++)
{
for (j = 0; j < HEIGHT; j++)
{
curMap[i][j] = tempMap[i][j];
}
}
}

就像大多数其他语言一样,在C语言中,任何非0的值都可以被认为是true。

if ( 20 ) {
// true
}
if ( -1 ) {
// true
}
if ( 'c' ) {
// true
}
if ( "string" ) {
// true
}
if ( 0 ) {
// false
}
if ( '' ) { // null terminator, a char with a value of 0
// false
}
if ( NULL ) { // value of a null pointer constant
// false
}

Bool只是一种使代码更易读的方法。

首先,一些注释

neighbors += curMap[...][...] == '*' ? 1 : 0

的多余写法
neighbors += curMap[...][...] == '*'

,因为比较运算符已经返回10

但都不如

清晰
if ( curMap[...][...] == '*' ) ++neighbors;

1表示真,0表示假;对吗?但是为什么没有bool呢?

不完全是。0为假(包括0作为指针,NULL)。


现在,进入问题。

但是为什么没有bool呢?

但有:_Bool.

stdbool.h提供了bool作为别名,以及宏truefalse

#include <stdbool.h>
#include <stdio.h>
bool flag = true;
if ( flag )
printf( "Truen" );
else
printf( "Falsen" );

编译器资源管理器演示

请注意,您发布的代码片段中的变量都不是布尔值,所以我不知道为什么该代码包含在您的问题中。

相关内容

  • 没有找到相关文章

最新更新