检查预处理器中整数类型的大小
如何在 g++ 下的预处理器中检查 unsigned
的大小? sizeof
是不可能的,因为它在预处理期间没有定义。
How can I check the size of an unsigned
in the preprocessor under g++? sizeof
is out of the question since it is not defined when during preprocessing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能不是最优雅的方法,但您可以利用的一件事是“limits.h”中定义的 UINT_MAX。也就是说,...
如果 UINT_MAX == 65535,那么您会知道 sizeof (unsigned) = 2
如果 UINT_MAX == 4294967295,那么您会知道 sizeof (unsigned) = 4。
依此类推。
正如我所说,它并不优雅,但它应该提供一定程度的可用性。
希望这有帮助。
This may not be the most elegant method, but one thing that you may be able to leverage is UINT_MAX defined in "limits.h". That is, ...
if UINT_MAX == 65535, then you would know that sizeof (unsigned) = 2
if UINT_MAX == 4294967295, then you would know that sizeof (unsigned) = 4.
and so on.
As I said, not elegant, but it should provide some level of usability.
Hope this helps.
根据 Sparky 的回答,这里有一种看起来更好的方法(通过消除显式数字)
定义INT_MAX
和< stdint.h>
定义UINT32_MAX
。一般来说,
< /a> 给出具有指定宽度的整数类型。Based on Sparky's answer, here is a way that would look a bit nicer (by eliminating the explicit numbers)
<limits.h>
definesINT_MAX
and<stdint.h>
definesUINT32_MAX
. Generally,<stdint.h>
gives integer types with specified widths.如果要检查表达式
sizeof(unsigned)
的值与某个数字是否相等,可以使用按位左移 (<<
) 。此操作仅适用于
unsigned
类型。如果你想检查条件
sizeof(unsigned) <= 32
,那么检查条件1 <<; 就足够了。 32==0
。因此,要测试条件
sizeof(unsigned) > 31
,需要测试1 << 31!= 0
。因此,要测试条件
sizeof(unsigned) == 32
,您可以使用以下命令:If you want to check the value of the expression
sizeof(unsigned)
on the equality with a certain number, you can use bitwise shift to the left (<<
).This operation just works with type
unsigned
.If you want to check condition
sizeof(unsigned) <= 32
, then it is enough to check the condition1 << 32 == 0
.Accordingly, to test the condition
sizeof(unsigned) > 31
, you need to test1 << 31 != 0
.As a result, to test the conditions
sizeof(unsigned) == 32
you can use this: