tags:

views:

125

answers:

1

Is there any way to compute length of va_list? All examples I seen the number of variable parameters is given explicitly.

+10  A: 

There is no way to compute the length of a va_list this is why you need the format string in printf like functions.

The only functions macros available for working with a va_list are:

  • va_start - start using the va_list
  • va_arg - get next argument
  • va_end - stop using the va_list

Please note that you need to call va_start and va_end in the same scope which means you can't wrap it in a utility class which calls va_start in its constructor and va_end in its destructor (I was bitten by this once).

For example this class is worthless:

class arg_list {
    va_list vl;
public:
    arg_list(const int& n) { va_start(vl, n); }
    ~arg_list() { va_end(vl); }
    int arg() {
        return static_cast<int>(va_arg(vl, int);
    }
};

GCC outputs the following error

t.cpp: In constructor arg_list::arg_list(const int&):
Line 7: error: va_start used in function with fixed args
compilation terminated due to -Wfatal-errors.

Motti
Hmm? No, it's perfectly allowable to call `va_start()`, then pass the `va_arg` to another function, then call `va_end()`. That's exactly how you use the `vsprintf()` and similar functions.
caf
@caf: In what universe does the va_list-instance in the case of using vsprintf() escape the scope?
Andreas Magnusson
@caf you're right, I didn't present this clearly, you don't have to call `va_arg` in the same scope as `va_start`. I've clarified my statement.
Motti