1 在-6ren">
gpt4 book ai didi

c - _Bool 有什么优势?

转载 作者:行者123 更新时间:2023-12-05 01:08:52 24 4
gpt4 key购买 nike

如果 _Bool 类型的行为类似于整数并且不强制值是真/假或 1/0,例如:

_Bool bools[] = {0,3,'c',0x17};
printf("%d", bools[2]);

> 1

在那里有什么好处?这是否只是一种简单的强制事物以查看它们如何评估“真实性”的方法,例如:

printf("%d\n", (_Bool) 3);
> 1

或者这对 C 语言有什么帮助或用处?

最佳答案

What advantage does _Bool give?

  1. _Bool 的值是 0 或 1。没有别的,不像 int .

  2. 转换为 _Bool始终将非零转换为 1,仅将 0 转换为 0。

When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

例子:

#include <math.h>
#include <stdlib.h>
_Bool all_false[] = { 0, 0.0, -0.0, NULL };
_Bool all_true[] = { 13, 0.1, 42.0, "Hello", NAN };

注意转换/强制转换为 int 的区别对比; _Bool : (int) 0.1 --> 0,但 (_Bool) 0.1 --> 1.

注意转换/强制转换为 unsigned 的区别对比; _Bool : (unsigned) 0x100000000 --> 0,但 (_Bool) 0x100000000 --> 1.

  1. _Bool增加 boolean 运算的清晰度。

  2. _Bool是来自 int 的独特类型, char等与 _Generic 一起使用时.

  3. 在 C99 之前,C 缺少 _Bool .许多早期代码形成了自己的类型bool, Bool, boolean, bool8, bool_t, ... .创建新类型 _Bool为这种常见但不统一的做法带来了统一性。 <stdbool.h>可以使用bool, true, false .这允许不包括 <stdbool.h> 的旧代码不破坏,但更新的代码使用更清晰的名称。


OP 的示例“不强制一个值为真/假或 1/0”确实强制 bools[2]值为 1。它没有强制 'c' 的初始化程序, 一个 int , 必须在 [0...1] 范围内,也不属于 _Bool 类型, 很像 int x = 12.345;被允许。在这两种情况下,都发生了转换。虽然第 2 次经常会产生警告。

关于c - _Bool 有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65650393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com