Last active
May 18, 2020 17:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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