Travier
Travier

Reputation: 225

C++ - Va_List (Variable Number Parameters) not casting properly

I've made a print function in C++ that should be a nicer alternative to std::cout, and it is very similar to the printf function in C.

The problem is that it receives a variable number of parameters, but uses them incorrectly.

Here's the source code:

void print(string s, ...)
{
    int len = s.length();
    int pSum = 0;
    for (int i = 0; i < len; i++)
    {
        if (s[i] == '%' && i < len - 1)
        {
            char c = s[i + 1];
            if (c == 'd' || c == 'i' || c == 's') pSum++;
        }
    }
    va_list ap; // Initialization of the VA list
    va_start(ap, pSum); // Start iterating through the VA list
    int r;
    for (int i = 0; i < len; i++)
    {
        if (s[i] == '%' && i < len - 1) // Check for % in the string
        {
            char c = s[i + 1];
            if (c == 'i') 
            {
                r = va_arg(ap, int);
                cout << r;
                i++;
            }
        }
        else cout << s[i];
    }
    va_end(ap); // Stop iterating over the VA list
    fflush(stdout); // Flush standard output stream
}

I tested this code that with that function call:

print("The number %i is the only even prime number.", 2);

And the output was:

The number -858993460 is the only even prime number.

Why does this happen? I have tried debugging but have absolutely no idea where does that problem come from.

Upvotes: 0

Views: 425

Answers (1)

Jarod42
Jarod42

Reputation: 218090

The second argument of va_start should be the last named parameter of the function so use:

va_start(ap, s);

Live example.

Upvotes: 2

Related Questions