簡體   English   中英

C 中的 1 和 0 一定是真還是假?

[英]Is 1 and 0 always have to be true or false in C?

最近發現一些代碼,我覺得很有趣,但是我不能正確理解它,所以有人可以給我解釋一下嗎?

這是康威的生命游戲。 我認為這一行可以像一個問題,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 ( '\0' ) { // 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( "True\n" );
else
   printf( "False\n" );

編譯器資源管理器上的演示

請注意,您發布的代碼段中的變量都不是布爾值,因此我不知道為什么該代碼包含在您的問題中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM