Hello guys my program is not printing the maximum value it is printing some garbage value or address.
#include <iostream>
#include <cstdarg>
int findmax(int, ...);
int main(int argc, char *argv[]) {
std::cout << findmax(9, 255, 86, 4, 89, 6, 1, 422, 5, 29);
}
int findmax(int count, ...) {
int max, val;
va_list list;
va_start(list, count);
for (int i = 0; i < count; i) {
max = va_arg(list, int);
val = va_arg(list, int);
if (max < val) max = val;
}
va_end(list);
return max;
}
CodePudding user response:
for (int i = 0; i < count; i) {
max = va_arg(list, int);
val = va_arg(list, int);
if (max < val) max = val;
}
In this code you take two arguments but iterate the index by one. va_arg
always takes the next element, so you end up with taking values beyond the variadic function argument list.
You may iterate by two elements, but this would require you to have even number of arguments, thus just declare a separate variable to store the max
element:
// std::numeric_limits is defined in <limits> header
auto max = std::numeric_limits<int>::min();
for (decltype(count) i = 0; i < count; i) {
auto val = va_arg(list, int);
if (max < val)
max = val;
}