UL后缀vs uint32_t转换 [英] UL suffix vs uint32_t cast
问题描述
我必须这样定义常量:
#define MY_CONSTANT 0xBEEF
我想确保我的常量将被视为32位.
I want to be sure that my constant will be considered 32 bits.
我可以像这样使用(uint32_t)转换:
I have can use a (uint32_t) cast like this :
#define MY_CONSTANT (uint32_t)0xBEEF
或者像这样的UL后缀:
Or a UL suffix like this :
#define MY_CONSTANT 0xBEEFUL
这两个版本完全相同吗?
Are these two versions fully equivalent?
我会说不,因为UL等同于 unsigned long
和 unsigned long
长度可能取决于CPU.
I would say no, as UL is the equivalent of unsigned long
and unsigned long
length may depend on CPU.
C99标准确保 uint32_t
整数为32位,但是我不认为这可以确保 UL
后缀具有相同的功能.
The C99 standard ensures that an uint32_t
integer is 32 bits, but I don't think it ensures that a UL
suffix does the same.
推荐答案
您是对的,由于您提到的原因,它们并不相同.不能保证 uint32_t
是 unsigned long
的别名.如有必要,在 #define
中包含演员表.
You're right, they're not equivalent for the reason you mention. There's no guarantee that uint32_t
is an alias for unsigned long
. Include the cast in the #define
s if necessary.
您应该使用括号,请参阅@Keith Thompson的评论,这是有充分理由的;否则 sizeof
将不起作用.
You should use the parentheses, see comment by @Keith Thompson for a very good reason why; otherwise sizeof
won't work.
这篇关于UL后缀vs uint32_t转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!