Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c++ - length of va_list when using variable list arguments?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  • va_copy (since C++11 and C99) - copy 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...