Question 6
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdarg.h>
#include <stdio.h>
double mean(int n, ...) {
va_list ap;
va_start(ap, n);
double s = 0;
for (int i = 0; i < n; i++)
s += va_arg(ap, double);
va_end(ap);
return s / n;
}
int main(void) {
printf("%.2f\n", mean(3, 4, 5, 9));
return 0;
}
- A mean must return float
- B n must be a double
- C There is no bug
- D The arguments 4, 5 and 9 are ints, but the function reads doubles – no conversion happens through ..., so the result is garbage (undefined behaviour); pass 4.0, 5.0, 9.0 Correct
Correct Answer: Option D
There is no prototype for the variable part, so the compiler cannot convert the arguments. The caller must pass exactly the type the function reads.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!