How to determine the end of va_arg list?

前端 未结 2 1464
情书的邮戳
情书的邮戳 2021-01-19 02:59

I have a function foo(char *n, ...); I need to get and use all of optional char parameters. I had an idea to use

while(va_arg(argP         


        
2条回答
  •  执念已碎
    2021-01-19 03:28

    The basic idea would work. But you've filled in the details in a way that almost certainly won't.

    The usual implicit conversion rules don't apply when you're using variadic arguments. Instead, default argument promotions take place, which means that any integer type smaller than int/unsigned int gets converted to one of those -- that's not the only promotion, but the only one relevant here -- and which also means that there is no automatic conversion to whatever type you specify with va_arg.

    This means that:

    • You cannot ever use va_arg(..., char), since it's impossible to pass a char as a variadic function argument.
    • You cannot ever pass NULL as a variadic function argument, since its concrete type is heavily implementation-dependent. Realistic types are int, long, void *, and there are loads of other less realistic but equally valid types.

    You could change

    while(va_arg(argPtr, char) != NULL)
    

    to

    while(va_arg(argPtr, int) != 0)
    

    and the call

    foo(n, 't', 'm', '$', NULL);
    

    to

    foo(n, 't', 'm', '$', 0);
    

提交回复
热议问题