Engineering Science 1036A/B Lecture 23: Pointers: References vs. Pointers
References
References are simpler, but restricted
Can only point to one object during its lifetime
must be initialized at the time of declaration
§
○
Cannot do any arithmetic
○
Used as an alias to another object
○
•
Declaring
int a;
int &b = a;
means &b=&a
○
bbecomes an alias of a
○
Grammar: reference variable must be initialized at the declaration statement
•
Using
int a;
int &b = a;
b = 5;
cout << b++ << endl; cout<< a << endl;
The following will result in a syntactical error:
int a;
int &b;
compilation error
§
b = a;
int &c = &a
compilation error
§
•
Grammar: Arrays of references are illegal
•
Pointers
Pointers are powerful and more complex
Can point to different objects during its lifetime
○
Can do “pointer arithmetic”
○
Uses additional syntax
○
•
Declaring
int *ptr_a;
int b, *iptr;
Using
iptr = &b;
Assign
○
*iptr = 5;
Use
○
cout << b << *iptr;
cout << iptr;
Call by Reference using referenced variables
after the call: int &x=a (&x=&a) and int &y=b (&y=&b)
x and y become the aliases of a and b
§
○
References vs. Pointers