curious question about a loop

in my code

#include <cstdlib>
#include <iostream>
#include <stack>

using namespace std;
void unionMerge(stack<int>& S, stack<int>& T);

int main()
{
stack <int> Q;
stack <int> P;

Q.push(5);
Q.push(7);
Q.push(8);
Q.push(9);

P.push(1);
P.push(2);
P.push(4);
P.push(6);

unionMerge(Q, P);

cout<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void unionMerge(stack<int>& S, stack<int>& T)
{
stack <int> tempDescending;
stack <int> mergenonDescending;

for(int x = 0; x<S.size() + T.size(); x++)
{

if(S.size()==0)
{
tempDescending.push(T.top());
T.pop();
}
else if(T.size()==0)
{
tempDescending.push(S.top());
S.pop();
}
else
{
if(S.top()>T.top())
{
tempDescending.push(S.top());
S.pop();
}
else
{
tempDescending.push(T.top());
T.pop();
}
}
}

while(tempDescending.size()!=0)
{
mergenonDescending.push(tempDescending.top());
cout<<mergenonDescending.top();
tempDescending.pop();
}
}

the loop thats bolded, when i write

for(int x = 0; x<S.size() + T.size(); x++)

i get a totally different answer to

for(int x = 0; x<8; x++)

BUT S.SIZE() + T.SIZE() DOES = 8.

but when i write for(int x = S.size() + T.size(); x>0; x--)
i get the same answer as for(int x = 0; x<8; x++) which is the right answer...

why ? thanks for the help
[2273 byte] By [muran] at [2007-11-20 11:02:14]
# 1 Re: curious question about a loop
In the first example the size() methods are called for each loop, in the second example they are just called once to initialize x.
S_M_A at 2007-11-9 1:24:55 >
# 2 Re: curious question about a loop
yes i know the difference but what im asking is... because S.SIZE() + T.SIZE() DOES EQUAL 8.. SO ITS THE SAME THING AS PUTTING 8.. BUt it doesnt work that way for some reason.

for(int x = 0; x<S.size() + T.size(); x++)

&

for(int x = 0; x<8; x++)

are different!! even tho S.size() + T.size() = 8

??
muran at 2007-11-9 1:25:55 >
# 3 Re: curious question about a loop
oh wait now i think i understand... if i use for(int x = 0; x<S.size() + T.size(); x++) , because im poping in the code, the SIZE of the each S and T keep changing so it wont stay with one value each loop
muran at 2007-11-9 1:27:02 >
# 4 Re: curious question about a loop
You'll need to cast to an int as .size() returns a 'size_type', not an int.

(int)S.size()

No he doesn't. He was correct that size() is evaluated each time through the loop and changes as the loop runs.
GCDEF at 2007-11-9 1:27:56 >
# 5 Re: curious question about a loop
You're absolutely right. Message retracted...

What I should have said was that he might try casting. I got in the habit of casting for types of 'size_type' and 'size_t' and haven't looked back.

But yes, it is an unsigned integral, after all...
Greggle at 2007-11-9 1:29:02 >
# 6 Re: curious question about a loop
what do u mean by it is an unsigned integral, after all...
muran at 2007-11-9 1:30:01 >
# 7 Re: curious question about a loop
It's a positive integer.

Sorry for any confusion...
Greggle at 2007-11-9 1:31:06 >