Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
int main() {
int a = 1;
int b = 2;
int& r = a;
int* p = &a;
r = b;
p = &b;
*p = 3;
std::cout << a << ' ' << b << '\n';
}2 3
- Expecting
1 3:r = b;does not re-bindrtob; it writes the value ofbintoa, whichrstill refers to. - Expecting
3 2: unlike a reference, a pointer can be pointed at another variable, so afterp = &b;the write*p = 3;changesb.
- Why can a pointer be left pointing at nothing, while a reference cannot?
- When would you pass a pointer to a function rather than a reference?