Engineering Science 1036A/B Lecture 23: Pointers: References vs. Pointers

14 views2 pages
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
§
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents