Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UL suffix vs uint32_t cast

Tags:

c

c99

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.

like image 280
ermitz Avatar asked Feb 18 '16 13:02

ermitz


1 Answers

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.

like image 111
unwind Avatar answered Nov 04 '22 21:11

unwind