UL suffix vs uint32_t cast

六眼飞鱼酱① 提交于 2021-02-18 22:12:52

问题


I have to define constants like this :

#define MY_CONSTANT   0xBEEF

I want to be sure that my constant will be considered 32 bits.

I have can use a (uint32_t) cast like this :

#define MY_CONSTANT   (uint32_t)0xBEEF

Or a UL suffix like this :

#define MY_CONSTANT   0xBEEFUL

Are these two versions fully equivalent?

I would say no, as UL is the equivalent of unsigned long and unsigned long length may depend on CPU.

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.


回答1:


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 #defines if necessary.

You should use the parentheses, see comment by @Keith Thompson for a very good reason why; otherwise sizeof won't work.




回答2:


The suffix corresponding to uint32_t is not necessarily UL (it's usually U on 32 bit and 64 bit architectures).

Apart from that, a cast might possibly truncate an integer constant that's wider, but its corresponding suffix wouldn't ever cast down, only up.

(See this table for how suffixes work with integer constants in different bases.)



来源:https://stackoverflow.com/questions/35483362/ul-suffix-vs-uint32-t-cast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!