Is using 0xFFFFFFFF a reliable way to set all bits in a 32-bit type?
There's this code that compiles with Windows SDK:
UINT cFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0);
where DragQueryFileW()
开发者_如何学运维has this signature:
UINT DragQueryFileW(HDROP, UINT, LPWSTR, UINT );
and UINT
is defined somewhere in SDK headers like this:
typedef unsigned int UINT;
for the platform where int
is surely 32-bits. As usual, types like UINT
are meant to have fixed width independent on the system bitness, so if the same code has to be recompiled on some other platform, where DragQueryFileW()
is reimplemented somehow there will also be a corresponding typedef
that will make UINT
map onto a suitable 32-bit unsigned type.
Now there's a static analysis tool that looks at 0xFFFFFFFF
constant and complains that it is an unportable magic number and one should use -1
instead. While of course -1
is good and portable I can't see how using the 0xFFFFFFFF
constant could be a problem here since even when porting the type will still be 32-bit and the constant will be fine.
Is using 0xFFFFFFFF
instead of -1
to set all bits safe and portable in this scenario?
The portable way to fill all bits (regardless of type size) is really:
type variable = (type)-1;
as in:
UINT foo = (UINT)-1;
or more portable using C99 type names:
uint32_t foo = (uint32_t)-1;
The C standard guarantees that assigning -1 sets all bits.
Now, if you can guarantee that your variable is unsigned 32 bits then using 0xFFFFFFFF
is alright as well, of course. But I'd still go for the -1
variant.
you could use:
type var = 0;
var = ~var;
One potential problem I see with 0xFFFFFFFF is that you can easily miss one F and initialize in a complete dummy value.
I believe that it is better to define a constant:
#define ALL_ONES_32BIT ((UINT) -1)
and use that everywhere.
0xffffffff is for sure a reliable way to set all bits to one in 32 bits. but I wouldn't depend on a UINT always being 32 bits.
to make it less "magic" you could also write it: (1 << 32) - 1
精彩评论