Question

Is it good practice to use unsigned suffix for negative constants in C++?

For example, is it safe to use,

foo(-1ull);

instead of

foo(unsigned long long(-1));
Was it helpful?

Solution

It is not really used "for negative constant". Constants (literals) in C++ are always non-negative. So, what you have here is literal 1ull with unary - operator in front of it. This means that the exact semantics of your first variant can be directly expressed as

-(unsigned long long) 1

but not as

(unsigned long long) -1

(although both produce the same result in the end).

BTW, your second variant, as written, is syntactically incorrect. "Multiword" type names cannot be used in functional-style casts. usigned(-1) is legal, but unsigned int(-1) is not. unsigned long long(-1) is also illegal.

But let's assume I understand what you tried to say by your second variant. Under that assumption, both variants do the same thing, so you can use either, depending on the personal preference or coding standard. The first one is obviously shorter though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top