There's a number of improvements that can be made.
You could use standard functions to make it clearer:
// Notice I made the return type an int instead of a float,
// since you're passing in ints
int smallest(int x, int y, int z){
return std::min(std::min(x, y), z);
}
Or better still, as pointed out in the comments:
int smallest(int x, int y, int z){
return std::min({x, y, z});
}
If you want it to operate on any number of ints, you could do something like this:
int smallest(const std::vector<int>& intvec){
int smallest = std::numeric_limits<int>::max(); // Largest possible integer
// there are a number of ways to structure this loop, this is just one
for (int i = 0; i < intvec.size(); ++i)
{
smallest = std::min(smallest, intvec[i]);
}
return smallest;
}
You could also make it generic so that it'll operate on any type, instead of just ints
template <typename T>
T smallest(const std::vector<T>& vec){
T smallest = std::numeric_limits<T>::max(); // Largest possible integer
// there are a number of ways to structure this loop, this is just one
for (int i = 0; i < vec.size(); ++i)
{
smallest = std::min(smallest, vec[i]);
}
return smallest;
}
INT_MAX
(orstd::numeric_limits<int>::max()
just start with the first number... – Prochronismconstexpr
. This looks like a better dup, even though itsmax
instead ofmin
: Most efficient way to find the greatest of three ints. It looks better because its C++ specific. But it lacks a good treatment of templates, meta programming andconstexpr
. – Curbing