gpt4 book ai didi

c++ - C++ 中的内置类型 bool 或 C 中的 stdbool.h 类型将 TRUE 和 FALSE 定义为不是机器字的大小?

转载 作者:太空狗 更新时间:2023-10-29 23:23:19 31 4
gpt4 key购买 nike

我的印象是 C 或 C++ 中的 bool 类型是 typdef'ed 整数,因为它在机器级别(字的大小等)处理起来“更容易”。但我只是执行了一个 sizeof,令我惊讶的是,它们返回了 1(字节)。这是正确的吗?好吧,根据我自己的简短实验,为什么一切都告诉我应该使用整数?

出于兴趣,请参阅 Wikipedia article关于 C 的 bool 数据类型。

最佳答案

C++11 规范,第 3.9.1 节 [basic.fundamental],第 6 段:

Values of type bool are either true or false. [Note: There are no signed, unsigned, short, or long bool types or values. — end note ] Values of type bool participate in integral promotions (4.5).

第 5.3.3 节 [expr.sizeof],第 1 段:

The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. The sizeof operator shall not be applied to an expression that has function or incomplete type, to an enumeration type whose underlying type is not fixed before all its enumerators have been declared, to the parenthesized name of such types, or to an lvalue that designates a bit-field. sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1. The result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined. [Note: in particular, sizeof(bool), sizeof(char16_t), sizeof(char32_t), and sizeof(wchar_t) are implementation-defined. (75) — end note ]

脚注 (75) 说:

75) sizeof(bool) is not required to be 1

脚注的存在表明 sizeof(bool) 在足够多的实现上等于 1,他们需要提醒人们这不一定如此。

关于c++ - C++ 中的内置类型 bool 或 C 中的 stdbool.h 类型将 TRUE 和 FALSE 定义为不是机器字的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17710421/

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