如果BOOL是int类型的宏,为什么它是一个不同的大小? [英] If bool is a macro for int, why is it a different size?

查看:149
本文介绍了如果BOOL是int类型的宏,为什么它是一个不同的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能解释为什么

I was hoping somebody could explain why

#include <stdbool.h>

printf("size of bool %d\n", sizeof(bool));
printf("size of int %d\n", sizeof(int));

输出

size of bool 1
size of int 4

我看了<一个href=\"http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html\">http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html这似乎表明,布尔本质上是_Bool宏,当设置为true或false,实际上只是一个整型常量的宏。如果它是一个整数,它为什么不一样大小?

I've looked at http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html which seems to indicate that bool is essentially a macro for _Bool which, when set to true or false, is really just a macro for an integer constant. If it is an integer, why is it not the same size?

我这么问是因为我们花了太长时间来调试程序,我们没有分配足够的内存。

I'm asking because it took us far too long to debug a program for which we did not allocate enough memory.

推荐答案

_Bool 键入C99(的typedef stdbool.h 编到布尔)没有一个标准的定义的大小,而是根据第6.2节。 C99标准的5:

The _Bool type in C99 (typedef'ed to bool in stdbool.h) doesn't have a standard defined size, but according to section 6.2.5 of the C99 Standard:

2 An object declared as type _Bool is large enough to store the values 0 and 1.

在C,最小的可寻址对象(除了位域)是字符,这至少是8位宽,和的sizeof(字符)总是 1

In C, the smallest addressable object (aside from bitfields) is the char, which is at least 8-bits wide, and sizeof(char) is always 1.

_Bool 布尔所以具有的sizeof 的至少 1 ,并且在我见过的大多数实现,的sizeof(布尔) / 的sizeof(_Bool) 1

_Bool and bool therefore have a sizeof of at least 1, and in most implementations that I've seen, sizeof(bool) / sizeof(_Bool) is 1.

如果你看一看GCC的 stdbool.h ,你会得到这样的:

If you take a look at GCC's stdbool.h, you'll get this:

 #define bool    _Bool
 #if __STDC_VERSION__ < 199901L && __GNUC__ < 3
 typedef int _Bool;
 #endif

 #define false   0
 #define true    1

因此​​,如果使用GCC的旧版本和旧版本的C标准的编译时,你会使用 INT _Bool 键入

当然,作为一个有趣的事情,检查了这一点:

Of course, as an interesting thing, check this out:

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

int main() {
   printf("%zu\n", sizeof(_Bool));
   printf("%zu\n", sizeof(true));
   printf("%zu\n", sizeof(false));

}

输出:

λ > ./a.out 
1
4
4

GCC 4.2.4,锵3.0,和GCC 4.7.0所有输出相同。由于trinithis指出,的sizeof(真)的sizeof(假)产生更大的尺寸,因为他们正在采取的大小一个int的文本,这至少是的sizeof(INT)

GCC 4.2.4, Clang 3.0, and GCC 4.7.0 all output the same. As trinithis points out, sizeof(true) and sizeof(false) produce larger sizes because they are taking the size of an int literal, which is at least sizeof(int).

这篇关于如果BOOL是int类型的宏,为什么它是一个不同的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆