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
MaxValueis 0xfff) and included (whenMaxValueis not 0xffff)? - Assuming you want to explicitly write an extra check to see if
MaxValueis equal to the limit the type can hold, is there a portable technique to use to identify the maximum value for the type ofMaxValuethat would work if later the code ofMaxValueis changed?- Meaning: how can I infer the maximum value of type via its variable name?
- I would prefer not using the
limits.hor<limit>constants likeUSHRT_MAX, or event not usingstd::numeric_limits<uint16>explicitly. - Can something like
std:numeric_limits<MaxValue>be used?
- I would prefer not using the
- Meaning: how can I infer the maximum value of type via its variable name?
typeid results in a type_info const & rather than the type of variable, use
instead.