bool 数据类型之谜
#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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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. Onlysizeof(char)
is guaranteed to be 1.2> It implicitly converts
int
tobool
:(bool)3 == 1
3> the array
b
is not initialized, it can have any value. You're just accessing some memory.最后一个 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.C 语言中没有真正的布尔类型。如果整数为 0 并且其他所有值都为 true,C 会将其解释为
false
。尽管布尔值只需要一位,但在实践中从未使用过,因为大多数架构中的最小可寻址单元是字节。使用我上面解释的方法,而不是沿着屏蔽一个字节中除一位以外的所有位的路线。您正在使用 C99 中的
stdbool.h
,它提供了 typedefbool
以及宏true
和false
。宏分别扩展为 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 typedefbool
and the macrostrue
andfalse
. The macros expand to 0 and 1 respectively but make the source more descriptive. Thesizeof
is implementation defined and you cannot rely on it to be the same on different platforms.