C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Fri, 18 Jul 2025 10:58:18 +0100
On Fri, Jul 18, 2025 at 10:22 AM Frederick Virchanza Gotham wrote:
>
> I forgot to add that _Max_t would also work properly with types
> smaller than int.


I'm just realising now that this is possible without core language
support. I'm going to put the following code in a header file and use
it in my programs.

Just the other day I nearly introduced a bug into a program . . . I
had a TCP port number stored in a uint16_t, and I wanted to check if
it was valid, so I compared it to 0 and also to -1 (in the hope that
-1 would be 65535). Thankfully the compiler gave me a warning that "-1
== n" would always be false because of integer promotion, and I fixed
it.

    #include <limits>
    #include <type_traits>

    struct _Max_t {
        template<typename T> requires std::is_integral_v<T>
        operator T(void) const
        {
            return std::numeric_limits<T>::max();
        }
        template<typename T> requires std::is_integral_v<T>
        bool operator==(T const n) const
        {
            return n == std::numeric_limits<T>::max();
        }
    } _Max;

    #include <iostream>
    using namespace std;

    int main(void)
    {
        short unsigned n = _Max;

        if ( _Max == n )
            cout << "equal\n";
        else
            cout << "not equal\n";
    }

Yeah I'm definitely using this from now on. I'm putting it inside "_Max.hpp".

Received on 2025-07-18 09:58:30