I need to create multiple functions that will check if an input is valid or not. Here are some of my codes:
bool IsValidRange(signed char s)
{
bool isValid = true;
if (!((s>=SCHAR_MIN)&&(s<=SCHAR_MAX)))
{
isValid = false;
}
return isValid;
}
bool IsValidRange(int s)
{
bool isValid = true;
if (!((s>=INT_MIN)&&(s<=INT_MAX)))
{
isValid = false;
}
return isValid;
}
I'm using the header limits.h for this. Am I doing this the right way? Please take note that I'm just a beginner. I hope you all will understand. Thank you!
First off, you don't need all those convolutions with booleans. Just return the expression directly:
Second, you should realize that both your functions always yield
true
: by definition, asigned char
is always in the range[SCHAR_MIN, SCHAR_MAX]
, and anint
is always in the range[INT_MIN, INT_MAX]
.But if you chose different bounds, this would indeed be the way to do it (taking into account my first remark).
As EdS. suggested, you could use a templated solution to reduce the number of functions/overloads you need: