Reputation: 225
This is probably a really silly question to experienced C++ developers, but what is the purpose of casting a -1 to uint32? I am translating a program from C++ to C# and there are many occasions when I see something like this:
static const uint32 AllTypes = static_cast<uint32>(-1);
What exactly does this do? How can the same be accomplished in C#?
Upvotes: 4
Views: 2371
Reputation: 263320
How can the same be accomplished in C#
uint AllTypes = uint.MaxValue;
Upvotes: 2
Reputation: 108840
On systems using two's complement, casting -1
to unsigned gives the highest value an unsigned number can represent.
In C# you can use unchecked((UInt32)-1)
or better: UInt32.MaxValue
. This is well defined behavior, and works on all CPU architectures.
According to the thread rve linked, casting -1
to unsigned results in all bits being set on all architectures in C++.
Upvotes: 4
Reputation: 60034
I guess it's used to have all bits to 1. Useful when we use tagged data. Probably each elementary type it's given a bit, and 'complex' types (arrays, for instance) get their own.
Upvotes: 1