Does 0xFFFFFFFF use a reliable way to set all bits in a 32-bit type?

Here is the code that compiles with the Windows SDK:

UINT cFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0); 

where DragQueryFileW() has this signature:

 UINT DragQueryFileW(HDROP, UINT, LPWSTR, UINT ); 

and UINT defined somewhere in the SDK headers as follows:

 typedef unsigned int UINT; 

for a platform where int is definitely 32-bit. As usual, types like UINT have a fixed width independent of the bit system, so if the same code needs to be recompiled on some other platform, where DragQueryFileW() redefined in some way, there will also be a corresponding typedef which will make the UINT card a suitable 32-bit unsigned type.

Now there is a static analysis tool that looks at the constant 0xFFFFFFFF and complains that it is an unsportsmanlike magic number, and -1 should be used instead . Although, of course, -1 is good and portable, I don’t see how there might be a problem with the constant 0xFFFFFFFF , because even when porting this type it will still be 32-bit, and the constant will be fine.

Uses 0xFFFFFFFF instead of -1 so that all bits are safe and portable in this scenario?

+6
source share
4 answers

Portable way to fill in all bits (regardless of font size):

 type variable = (type)-1; 

how in:

 UINT foo = (UINT)-1; 

or more portable using names like C99:

 uint32_t foo = (uint32_t)-1; 

The C standard ensures that assignment -1 sets all bits.

Now, if you can guarantee that your unsigned variable is 32 bits, then, of course, using 0xFFFFFFFF is okay too. But I will still use the -1 option.

+12
source

you can use:

 type var = 0; var = ~var; 
+4
source

One potential problem that I see with 0xFFFFFFFF is that you can easily skip one F and initialize to a full dummy value.

I find it better to define a constant:

 #define ALL_ONES_32BIT ((UINT) -1) 

and use it everywhere.

+3
source

0xffffffff is a reliable way to set all bits to one of 32 bits. but I will not depend on UINT, which is always 32 bits.

to make it less “magical”, you can also write it: (1 <32) - 1

+2
source

Source: https://habr.com/ru/post/891516/


All Articles