C语言中bool和while(true)的区别

Difference between bool and while (true) in C

我才知道 boolboolwhile (true)while (1) 似乎都是同一个无穷函数。 boolwhile (true)while (1) 有什么优势吗?我看不出有什么区别。

布尔值:

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

int main(void) 
{
    bool keep_going = true;  // Could also be `bool keep_going = 1;`
    while(keep_going) 
    {
        printf("This will run as long as keep_going is true.\n");
        // keep_going = false;    
        // Could also be `keep_going = 0;`
    }

    printf("Stopping!\n");
    return EXIT_SUCCESS;
}

While(true) 是一个无限循环。布尔值是一种具有真值和假值的数据类型。如果您想在任何阶段更改为 false,则使用 Bool。所以你可以改变for循环里面bool的值来停止循环。

C 评估所有 non-zero as true 的数字,而零被视为 false。所以while(true)while(1)是完全一样的。