0

Came across a code that's working but cannot figure out why

#include<stdio.h>
#include<stdarg.h>
void fun(char *msg, ...);

int main()
{
    fun("ABCDEFG", 1, 4, 7, 11, 0);
    return 0;
}
void fun(char *msg, ...)
{
    va_list ptr;
    int num;
    va_start(ptr, msg);
    num = va_arg(ptr, int);
    num = va_arg(ptr, int);
    printf("%d", num);
}

Can anybody tell me what does ... in the function fun stand for ? And when do we use it ?

3
Contributors
2
Replies
21
Views
2 Years
Discussion Span
Last Post by cgeier
0

... at the end of a function's parameter list says that the function takes a variable number of arguments. I'll leave it at that so you can try to figure out why it works, then I can tell you how it works. :)

One thing to note though is that the variable arguments are not type checked. Hence why printf (which is a variable argument function) uses the format string to determine the type of the argument.

As for when to use it...rarely, in my experience. The negatives tend to outweight the positives, but if you have a situation like printf or scanf, then variable parameters can be a useful solution.

Edited by deceptikon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.