tracing the output

I fully understand the output for the first function calling but I don't understand the output for the second function call.
it displays in function: x=4 y=3 z=4 but I don't understand why. can anyone explain it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
using namespace std;

void surprise(int  z, int x, int y);

int main()
{
    int x=1, y=2, z=3;
    surprise(x, y, z);
    cout<< "in main: x="<<x << " y=" << y << " z=" << z << endl;
	surprise(z, z, x);
    cout<< "in main x="<<x << " y=" << y << " z=" << z << endl;

}

void surprise(int z, int x, int y)
{
    z++;
    x = z * y;
	y = x - 1;
	cout<< "in function: x="<<x<<" y="<<y << " z=" << z << endl;
     
Line 11 is the same as
 
  surprise (3, 3, 1);

At line 17: z=3, x=3, y=1
After line 18, z is 4.
After line 19, x is 4 (4 * 1)
After line 20, y is 3 (4 - 1)

So at line 21: x=4, y=3, z=4 is correct
Last edited on
Hello Ryoka117,

Maybe this will help to explain a little better:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

void surprise(int  z, int x, int y);

int main()
{
	int x = 1, y = 2, z = 3;

	std::cout << "\nSending \"x\" as " << x << " \"y\" as " << y << " and \"z\" as " << z << std::endl;
	surprise(x, y, z);  // Sending 1, 2, 3
	cout << "in main: x=" << x << " y=" << y << " z=" << z << endl;

	
	std::cout << "\nSending \"z\" as " << z << " \"z\" as " << z << " and \"x\" as " << x << std::endl;
	surprise(z, z, x);  // Sending 3, 3, 1
	cout << "in main x=" << x << " y=" << y << " z=" << z << endl;

	return 0;
}

// Second time through receiving 3, 3, 1
void surprise(int z, int x, int y)
{
	z++;
	x = z * y;
	y = x - 1;
	cout << "in function: x=" << x << " y=" << y << " z=" << z << endl;
}


BTW your above code is missing the closing } of the function.

Hope that helps,

Andy

Edit:
Last edited on
thanks, I was looking at it all wrong
Topic archived. No new replies allowed.