Anatoly
Anatoly

Reputation: 1916

Conversions from Unsigned Integral Types style. Is this style good?

Many times I see programmers doing the following cast

unsigned long long minimumValue;
minimumValue = (unsigned long long)-1;

but why do they do this, rather than int minimumValue = -1?

Upvotes: 1

Views: 66

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

That's a trick to give the maximum (not minimum) value of an unsigned type. Conversion from a signed value uses modular arithmetic to give a value in the range of the unsigned type; so -1 becomes pow(2,N)-1 for an unsigned type with N bits, which is the largest representable value.

The cast isn't strictly necessary, but some compilers might give a warning without it.

A better style might be to specify ULLONG_MAX, or std::numeric_limits<unsigned long long>::max() in C++.

Upvotes: 5

Related Questions