trace code to predict outcome. Byref

So I have this code

void testOne(int one, int &two)
int main()
{
int num=10, prod=15;

cout<<num<<""prod<<endl;

testOne(num,prod);
cout<<num<<""<<prod<<endl;"

testOne(prod,num);
cout<<num<<""<<prod<<endl;

return 0;
}


void testOne(int one, int &two)
{
cout<<one<<""<<two<<endl;
one=two*2
two=two*3
cout<<one<<""<<two<<endl;
}

the answers are

10 15
10 15
30 45
10 45
45 10
20 30
30 45.


when the 45 and the ten switch positions, I get kind of lost. I understand what byRef means, and I see the switch in the body, I'm just confused as to why the switch occurs there without displaying 10 45 again before the switch. Can anyone walk me through this?

First off, you have some syntax errors in your program.
Line 6 - missing << between "" and prod.
Line 9 - extraneous " at end of line
Line 21, 22 - Missing ;

After correcting the syntax errors, the program runs as follows:
10 15 - Before first call
10 15 - First display inside testOne
30 45 - After multiplication
10 45 - After return. num (1st arg) unchanged. prod (2nd arg) changed.
45 10 - First display inside testone shows arguments reversed.
20 30 - After multiplication
30 45 - After second call. prod (1st arg) unchanged. num (2nd arg) changed.

I'm just confused as to why the switch occurs there without displaying 10 45 again before the switch

Why would it? There is only one display where the numbers are 10,45 and that is after returning from testOne the first time.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
http://v2.cplusplus.com/articles/jEywvCM9/
It makes it easier to read your code and it also makes it easier to respond to your post.
Last edited on
The last three is where I'm getting confused. after "return.num(1st arg) unchanged. prod (2nd arg) changed." the numbers are reversed due to the (prod,num) argument, which I get.

Then after multiplication, the 10 in prod is called byref and multiplied, which results in a 30, but at the end, how do we get back to 30 45?
In the final cout (before the return 0), you're displaying num and prod in that order.
Since num (10) was passed as the second argument, it was multiplied by three resulting in 30. prod (45) was passed as the first argument, so it was unchanged.
When num and prod were displayed in the last cout, you got 30,45 as you should.
Topic archived. No new replies allowed.