LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Predict the Output · Question 12

C23 variadic function with no named parameter Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following program, compiled as C23?

main.c
#include <stdarg.h>
#include <stdio.h>

int product(...) {
    va_list ap;
    va_start(ap);
    int n = va_arg(ap, int);           /* the first argument is the count */
    int p = 1;
    while (n-- > 0)
        p *= va_arg(ap, int);
    va_end(ap);
    return p;
}

int main(void) {
    printf("%d %d\n", product(3, 2, 3, 7), product(0));
    return 0;
}
  • A 126 0
  • B 42 0
  • C 42 1 Correct
  • D Compilation error
Correct Answer: Option C

C23 accepts a parameter list of just ..., and va_start(ap) needs no named parameter. The count is simply read as the first variable argument; an empty product is 1.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links