# Simple Function Pointers - Determining Output

• 12-07-2007
Simple Function Pointers - Determining Output
Trace the following program to determine its output.
Code:

```#include <iostream> using namespace std; void foo (int *a, int *b) {     *a = *a + *b;     *b = *b + 2;     cout << "a:" << *a << " b:" << *b << endl; } int main () {     int a = 5;     int b = 4;     foo(&a,&b);     foo(&b,&a);     cout << "a is: " << a << " b is:" << b << endl; }```
If somebody could go through and specify when each a,b,*a, and *b changes in the function main, or foo, that would be great.

If I were to analyze it right now, I would say the 5 and 4 get passed into the foo function, and then *a = *a + *b; changes the a in the main function to 9, and the *b = *b + 2; changes the b in the main function to 6. Then the output from void foo would be a: 5 b: 4 (not sure about that)

Then the 2nd time they are brought up as 6 and 9. The *a = *a + *b; changes the a in the main function from 9 to (6+9) = 15 and the *b = *b + 2; changes the b in the main function from 6 to (9+2) = 11. The output from void foo this time would be a: 6 b: 9

Then the output from main would be a is: 15 b is: 11

I'm not sure if that's correct so if somebody could go through it and describe what is happening at each point similarly to what I did that would be great.

Thanks!
• 12-07-2007
grumpy
Quote:

If somebody could go through and specify when each a,b,*a, and *b changes in the function main, or foo, that would be great.

I'm not going to do that, as that would effectively be doing your homework for you. Instead, since you've had a try, I'll give pointers to where your arguments are mistaken. That way, you can think things through, and have the satisfaction of getting correct answers for yourself.
Quote:

If I were to analyze it right now, I would say the 5 and 4 get passed into the foo function, and then *a = *a + *b; changes the a in the main function to 9, and the *b = *b + 2; changes the b in the main function to 6.

Your logic is correct to here.
Quote: