Understanding References

References could be used to:
a) define pointer to a memory location
b) pass pointer arguments to a function
c) access the value without and asterix (*)

Are any of the above true? I used the site posted below and I've learned that references are like int aliases. References are also the object. Which do not fit any of the descriptions above.

Am I correct in thinking a,b, and c are all false?

http://www.parashift.com/c++-faq/overview-refs.html

Here's an example of reference I used

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void swap(int& i, int& j)
{
  int tmp = i;
  i = j;
  j = tmp;
}

int main()
{
  int x, y;
  ...
  swap(x,y);
  ...
}
Last edited on
The important thing to remember is that the reference operator returns the memory address of the variable/object.
a) You initialize and assign memory addresses to pointers which then can be dereferenced.
b) The function parameter will hold a copy of its type, which is a pointer in this case. Therefore, any memory address stored in a pointer passed to a function will also be dereference-able by the function's parameter.
c) Pretty iffy, so I agree with you there. Indeed, reference variables can be used as aliases to variables (not just ints). Therefore, you are using the same variable without having to use pointers.

I would say c is definitely false though a is worded a little off. In fact, its just the wording that kind of sets them off.
A reference is an alias for a variable.

a) False, although taking the address of a reference will give you the address of the aliased variable.

b) True. Pointers may be passed by reference the same as any other type.

c) In the sense that a reference and a pointer are both indirect ways to get to a thing, one needs to dereference a pointer (sometimes via *) to get past the indirection and such a thing is not required for a reference. The wording didn't make much sense to me.

@Daleth: Pointers are not references.
I was saying that the memory address from the passed pointer variable will be used to initialize to function's parameter. So the address can be dereferenced by the pointer?

Edit:
Okay, maybe I was saying it a bit weird. I was talking about:
1
2
3
4
5
6
7
8
9
10
11
12
void funky(int* param){}
//...
int main(){
   int y;
   int* ptr = &y;
   funky(ptr);
/*
   Causes:
   -   param = ptr
   -   now *param will access y
*/
}
Last edited on
Daleth wrote:
I was saying...

The subject of this thread is references. Pointers are not references. There are no references in your code, but there is a fine example of passing a pointer by value.
Topic archived. No new replies allowed.