c++numeric-limits

In C++, how to express the largest possible value of a type via its variable name?


Assuming there is a declaration in a header file you don't control that states something like:

static const uint16 MaxValue = 0xffff;  // the type could be anything, static or not 

Inside a file that includes the above you have code like this:

int some_function(uint16 n) {
   if (n > MaxValue) {
     n = MaxValue;
   }
   do_something(n);
   ...
}

The compiler will warn that the if statement is always false because n cannot be larger than 0xffff.

One way might be to remove the code. But then if later someone wants to change the value of MaxValue to something lower you have just introduced a bug.

Two questions:


Solution

  • typeid results in a type_info const & rather than the type of variable, use

    std::numeric_limits<decltype(variable)>::max()
    

    instead.