Are there gotchas using varargs with reference parameters

Posted by Roddy on Stack Overflow See other posts from Stack Overflow or by Roddy
Published on 2008-10-21T14:58:27Z Indexed on 2010/03/31 22:03 UTC
Read the original article Hit count: 500

Filed under:
|
|

I have this piece of code (summarized)...

AnsiString working(AnsiString format,...)
{
    va_list argptr;
    AnsiString buff;

    va_start(argptr, format);
    buff.vprintf(format.c_str(), argptr);

    va_end(argptr);
    return buff;
}

And, on the basis that pass by reference is preferred where possible, I changed it thusly.

AnsiString broken(const AnsiString &format,...)
{
... the rest, totally identical ...
}

My calling code is like this:-

AnsiString s1, s2;
    s1 = working("Hello %s", "World");
    s2 = broken("Hello %s", "World");

But, s1 contains "Hello World", while s2 has "Hello (null)". I think this is due to the way va_start works, but I'm not exactly sure what's going on.

© Stack Overflow or respective owner

Related posts about c++

Related posts about varargs