C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Using -1 as the max value for an unsigned integer

From: Ted Lyngmo <ted_at_[hidden]>
Date: Mon, 18 Aug 2025 19:17:48 +0200
Den 2025-07-18 kl. 11:15, skrev Frederick Virchanza Gotham via
Std-Proposals:
> And it's annoying when a compiler emits a warning for "-1 == n" to say
> that I'm comparing signed with unsigned.
>
> I wonder could we standardise some shorthand for this?

`if (n == -1uz)` - but MSVC warns about that.

Another way that you could define yourself (except you shouldn't use a
reserved identifier):
```
inline constexpr struct {} _Max;

template <class T>
constexpr auto operator<=>(decltype(_Max), T other) {
     return std::numeric_limits<T>::max() <=> other;
}
template <class T>
constexpr bool operator==(decltype(_Max), T other) {
     return std::numeric_limits<T>::max() == other;
}
```
But I don't really see a compelling reason _not_ to use `npos` which is
defined specifically for this situation. Sure, `_Max` is shorter, but still.

Br,
Ted

Received on 2025-08-18 17:17:54