bool 数据类型之谜

发布于 2024-12-10 15:26:52 字数 592 浏览 0 评论 0原文

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

int main()
{
bool a[5]={0,1,0,0,0};
a[1]=3;
printf("\n bool is %d",a[1]);
printf("\n sizeof bool is %d and size of a is %d",sizeof(bool),sizeof(a));

bool b[10];
printf("\n bool is %d",b[1]);

}

该程序的输出是

 bool is 1
 sizeof bool is 1 and size of a is 5
 bool is 4

问题:

1> bool 存储 1 位那么为什么 sizeof(bool) 是 1 个字节?

2>如果 bool 有 1 个字节那么当我分配 a[1] = 3 时为什么它打印 1 ?

3> if bool 只考虑 1 & o 要存储的值那么为什么 b[1] 打印值 3 ?

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

int main()
{
bool a[5]={0,1,0,0,0};
a[1]=3;
printf("\n bool is %d",a[1]);
printf("\n sizeof bool is %d and size of a is %d",sizeof(bool),sizeof(a));

bool b[10];
printf("\n bool is %d",b[1]);

}

output of this program is

 bool is 1
 sizeof bool is 1 and size of a is 5
 bool is 4

Question :

1> bool store 1 bit then why sizeof(bool) is 1 byte ?

2> if bool has 1 byte then when i assign a[1] = 3 then why it print 1 ?

3> if bool only consider 1 & o value to be store then why b[1] prints value 3 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅暮の光 2024-12-17 15:26:52

1> Bool 存储不是 1 位。没有什么是 1 位。一切都至少是 1 字节。 sizeof(bool) 是特定于平台的。仅保证 sizeof(char) 为 1.

2>它隐式地将 int 转换为 bool(bool)3 == 1

3>数组b未初始化,它可以有任何值。您只是访问一些内存。

1> Bool store is not 1 bit. Nothing is 1 bit. Everything is at least 1 byte. sizeof(bool) is platform specific. Only sizeof(char) is guaranteed to be 1.

2> It implicitly converts int to bool : (bool)3 == 1

3> the array b is not initialized, it can have any value. You're just accessing some memory.

原来分手还会想你 2024-12-17 15:26:52

最后一个 printf 打印 4 的原因是因为 b 数组未初始化,这意味着 printf 函数仅采用内存中已有的值。

The reason the last printf prints a 4, is because the b array is not initialized, which means the printf-function just takes whatever value is already in the memory.

你是暖光i 2024-12-17 15:26:52

C 语言中没有真正的布尔类型。如果整数为 0 并且其他所有值都为 true,C 会将其解释为 false。尽管布尔值只需要一位,但在实践中从未使用过,因为大多数架构中的最小可寻址单元是字节。使用我上面解释的方法,而不是沿着屏蔽一个字节中除一位以外的所有位的路线。

您正在使用 C99 中的 stdbool.h,它提供了 typedef bool 以及宏 truefalse。宏分别扩展为 0 和 1,但使源代码更具描述性。 sizeof 是实现定义的,您不能依赖它在不同平台上是相同的。

In C there is no real boolean type. C interprets an integer to mean false if it is 0 and everything else as true. Even though a bool would only require a single bit, this is never used in practice as the smallest addressable unit in most architectures is a byte. Instead of going down the route of masking all but one bits in a byte the approach I explained above is used.

You are using stdbool.h from C99 which is providing a typedef bool and the macros true and false. The macros expand to 0 and 1 respectively but make the source more descriptive. The sizeof is implementation defined and you cannot rely on it to be the same on different platforms.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文