Skip to content

Instantly share code, notes, and snippets.

@DalyaG
Last active May 18, 2020 17:28
Show Gist options
  • Save DalyaG/a1bf3077cd7c350412388caa87cbca72 to your computer and use it in GitHub Desktop.
Save DalyaG/a1bf3077cd7c350412388caa87cbca72 to your computer and use it in GitHub Desktop.
Pointers and references in C++: what happens when b points to an alias of a
#include <iostream>
using namespace std;
void change_val(int &z);
int main() {
int a = 1;
int *b = &a;
cout << "b points to an alias of the integer a\n";
cout << "a=" << a << ", b=" << b << ", *b=" << *b << endl;
// prints: a=1, b=0x7fffd3bf5de8, *b=1
change_val(a);
cout << "Function change_val gets an alias of a as input, ";
cout << "and so changing the value of a inside the function, also changes a.\n";
cout << "Furthermore, when a changes, so does the value that b points to:\n";
cout << "a=" << a << ", b=" << b << ", *b=" << *b << endl;
// prints: a=2, b=0x7fffd3bf5de8, *b=2
}
void change_val(int &z) {
z++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment