Home > Software engineering >  In C , how to express the largest possible value of a type via its variable name?
In C , how to express the largest possible value of a type via its variable name?

Time:11-24

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:

  • Is there any C templates or techniques that can be used to make sure the code is removed when not needed (because MaxValue is 0xfff) and included (when MaxValue is not 0xffff)?
  • Assuming you want to explicitly write an extra check to see if MaxValue is equal to the limit the type can hold, is there a portable technique to use to identify the maximum value for the type of MaxValue that would work if later the code of MaxValue is changed?
    • Meaning: how can I infer the maximum value of type via its variable name?
      • I would prefer not using the limits.h or <limit> constants like USHRT_MAX, or event not using std::numeric_limits<uint16> explicitly.
      • Can something like std:numeric_limits<MaxValue> be used?

CodePudding user response:

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

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

instead.

CodePudding user response:

Try this:

std:numeric_limits<decltype(n)>::max()
  • Related