How to count the number of arguments passed to a function that accepts a variable number of arguments?

前端 未结 10 2144
旧时难觅i
旧时难觅i 2020-12-01 05:18

How to count the no of arguments passed to the function in following program:

#include
#include
void varfun(int i, ...);
int m         


        
10条回答
  •  情话喂你
    2020-12-01 05:33

    You can't. varargs aren't designed to make this possible. You need to implement some other mechanism to tell the function how many arguments there are. One common choice is to pass a sentinel argument at the end of the parameter list, e.g.:

    varfun(1, 2, 3, 4, 5, 6, -1);
    

    Another is to pass the count at the beginning:

    varfun(6, 1, 2, 3, 4, 5, 6);
    

    This is cleaner, but not as safe, since it's easier to get the count wrong, or forget to update it, than it is to remember and maintain the sentinel at the end.

    It's up to you how you do it (consider printf's model, in which the format string determines how many — and what type — of arguments there are).

提交回复
热议问题