I started writing this code a few days ago. I saw a question on here that got me wondering about variable argument lists, so I wrote (never really finished, but it has the functionality I was curious about) this piece of code:
void VendingMachine::setStamps(int largest, ...)
{
cout << "Setting stamps to: \n";
vector<int> tmp;
vector<int>::iterator iter;
int next = largest;
va_list lst;
va_start(lst, largest);
while(next != NULL)
{
cout << next << "\n";
tmp.push_back(next);
next = va_arg(lst,int);
}
va_end(lst);
stamps = new int[tmp.size()-1];
int i = 0;
for(iter = tmp.begin(); iter != tmp.end();)
{
stamps[i] = *iter;
iter++;
i++;
}
cout << "The array is now: ";
showStamps();
}
void VendingMachine::showStamps()
{
cout << sizeof(stamps) << " " << sizeof(*stamps);
for(int i = 0; i < NUM_OF(stamps); i++)
cout << stamps[i] << ", ";
cout << "\n";
}
Now, what I’d expect is for setStamps to never finish. Or at least take a very long time, and a variable amount of time, since no part of the list is guaranteed to be NULL unless it was supplied. This isn’t the case. I call setStamps with v.setStamps(90,30,24,15,12,10,5,3,2,1); and it prints this out:
Setting stamps to:
90
30
24
15
12
10
5
3
2
1
-217832717
The array is now: 4 490,
Ignoring the last line, since that was me messing around trying to figure out how to determine the length of an array, this doesn’t make sense. It stopped after the first value that was outside of the passed arguments. It should have kept going until there was a NULL value, and there shouldn’t be one of those in the same place each time. But the outcome is always the same: 90, 30, 24, 15, 12, 10, 5, 3, 2, 1, [number that changes each time]. There’s never any additional values. It’s a mystery.
Who says there won’t be one in the same place every time? The behavior is undefined, and so having a NULL value in the same place every time is entirely possible.