Reference/Pointer Question

Hello,

I have the following program:
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
#include <iostream>
using namespace std;

void foo(int, int&, int, int *);

int main(){

	int x = 5, y = 10, z = 3;
	int *p;

	p = &x;

	cout << "x = " << x << ", y = " << y << ", z = " << z << ", p = " << p << endl;
	foo(x,y,z,p);
	cout << "x = " << x << ", y = " << y << ", z = " << z << ", p = " << p << endl;

	return 0;
}

void foo(int a, int &b, int c, int *d){

	a = c;
	b = a * a;
	c = 5;
	*d = a * b + c;
}


and I'm a bit confused with the function's parameter int &b. Is that the same as int *b?

Also, during the function call, it looks to me that 'a' is supposed to be set to 'c', which is 3, but I've run it in debug mode, and while in the function, 'a' is never set to 3. Am I seeing something wrong here?

Thanks,
Chris
While int& and int* are somewhat different in what they mean and certainly different in how you work with them, they are often used for the same purpose. Prefer int&, as it is cleaner.

If you traced the program and didn't find 3 written to a, it could be that a was optimised out and replaced by c. That is okay because it makes no difference to the output.
closed account (1vRz3TCk)
capei wrote:
I'm a bit confused with the function's parameter int &b. Is that the same as int *b?

No, conceptually a reference (int &b) is another name for an existing variable. Here is a attempt to draw the function call (foo(x,y,z,p);)as a diagram:

Function   |   Main
Scope      |   Scope
           |
A +-----+  |   X +-----+
  |  5  |  |     |  5  |<-+<-+
  +-----+  |     +-----+  |  |
           |              |  |
B --+      |   Y +-----+  |  |
    +------|---->|  10 |  |  |
           |     +-----+  |  |
           |              |  |
C +-----+  |   Z +-----+  |  |
  |  3  |  |     |  3  |  |  |
  +-----+  |     +-----+  |  |
           |              |  |
D +-----+  |   P +-----+  |  |
  |  @--|--|-+   |  @--|--+  |
  +-----+  | |   +-----+     |
           | +---------------+
           |
           |

Here;
A is a copy of X, if you change the value of A it does not change the value of X.
B is a reference to Y (another name for Y), anything done to B is actually done to Y.
C is a copy of Z, if you change the value of C it does not change the value of Z.
D is a copy of P, as p points to X, so does D. If you dereference D and change its value you will change the value of X, If you change what D points to you will not change what P points to.
Last edited on
Thanks so much for the reply's and the well-drawn out diagram! It was very helpful!

It seems 'a' was getting changed, since 'b' was changed to '9', although my debugger didn't show it at first.

That diagram was a big help, though, so thanks for taking the time to explain.

:-)

Many thanks,
Chris
Topic archived. No new replies allowed.