Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DalyaG/d9323bbf1aa77619791dab97ece027eb to your computer and use it in GitHub Desktop.
Save DalyaG/d9323bbf1aa77619791dab97ece027eb to your computer and use it in GitHub Desktop.
Pointers and references in C++: what happens when c takes the value that b points to
#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 integer that takes the value that 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 does not change anything else\n";
cout << "a=" << a << ", b=" << b << ", *b=" << *b << ", c=" << c << endl;
// prints: a=1, b=0x7fffd3bf5de8, *b=1, c=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