c# 在C中1和0总是真还是假?

55ooxyrt  于 2022-12-09  发布在  C#
关注(0)|答案(1)|浏览(285)

最近我发现了一些我很感兴趣的代码,但是我不能正确地理解它,所以有人能给我解释一下吗?
这是康威的生命游戏。我想这一行可以像一个问题,1表示真,0表示假;对吗?2但是为什么没有布尔值呢?

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];
        }
    }
}
a11xaf1n

a11xaf1n1#

First, a couple of comments.

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

is a redundant way of writing

neighbors += curMap[...][...] == '*'

since the comparison operators already return 1 or 0 .
But neither are as clear as

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

1 meaning true and 0 meaning false; is that correct? But why is there no bool?
Not quite. 0 is false (including 0 as a pointer, NULL ). All other values are true.
Now, on to the question.
But why there is no bool?
But there is: _Bool .
stdbool.h provides bool as an alias, as well as the macros true and false .

#include <stdbool.h>
#include <stdio.h>

bool flag = true;

if ( flag )
   printf( "True\n" );
else
   printf( "False\n" );

Demo on Compiler Explorer
Note that none of the variables in the snippet you posted are booleans, so I have no idea why that code was included in your question.

相关问题