Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DalyaG/b0311fc41f41474a9c5e386277211514 to your computer and use it in GitHub Desktop.
Save DalyaG/b0311fc41f41474a9c5e386277211514 to your computer and use it in GitHub Desktop.
Pointers and references in C++: what happens when c is an alias to the pointer b
#include <iostream>
using namespace std;
void change_val(int &z);
int main() {
int a = 1;
int *b = &a;
int &c = *b;
cout << "c is an alias of whatever b points to\n";
cout << "a=" << a << ", b=" << b << ", *b=" << *b << ", c=" << c << endl;
// prints: a=1, b=0x7fffd3bf5de8, *b=1, c=1
change_val(c);
cout << "changing c also changes what b points to, which is an alias of a\n";
cout << "a=" << a << ", b=" << b << ", *b=" << *b << ", c=" << c << endl;
// prints: a=2, b=0x7fffd3bf5de8, *b=2, c=2
change_val(*b);
cout << "in a similar manner, changing what b points to also changes a and c\n";
cout << "a=" << a << ", b=" << b << ", *b=" << *b << ", c=" << c << endl;
// prints: a=3, b=0x7fffd3bf5de8, *b=3, c=3
}
void change_val(int &z) {
z++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment