Created
May 31, 2012 02:30
-
-
Save stephenmm/2840556 to your computer and use it in GitHub Desktop.
Working example of passing by value, reference and pointer in every combination.
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
// g++ passing_by_example.cpp -o passing_by_example.x && ./passing_by_example.x | |
#include <iostream> | |
using namespace std; | |
int main(){ | |
int Bats = 1; | |
int *pB = &Bats; | |
int& rB = Bats; | |
void PassByValue(int b); | |
void Reference(int &b); | |
void Pointers(int *b); | |
cout << "\nAt startup, within main() \tBats \t = " << Bats << endl; | |
cout << endl; | |
PassByValue(Bats); | |
cout << "After calling PassByValue(Bats) Bats \t = " << Bats << endl; | |
PassByValue(rB); | |
cout << "After calling PassByValue(rB) \tBats \t = " << Bats << endl; | |
PassByValue(*pB); | |
cout << "After calling PassByValue(*pB) \tBats \t = " << Bats << endl; | |
cout << endl; | |
Reference(Bats); | |
cout << "After calling Reference(Bats) \tBats \t = " << Bats << endl; | |
Reference(rB); | |
cout << "After calling Reference(rB) \tBats \t = " << Bats << endl; | |
Reference(*pB); | |
cout << "After calling Reference(*pB) \tBats \t = " << Bats << endl; | |
cout << endl; | |
Pointers(&Bats); | |
cout << "After calling Pointers(&Bats) \tBats \t = " << Bats << endl; | |
Pointers(pB); | |
cout << "After calling Pointers(pB) \tBats \t = " << Bats << endl; | |
Pointers(&rB); | |
cout << "After calling Pointers(&rB) \tBats \t = " << Bats << endl; | |
cout << endl; | |
} | |
void PassByValue(int b){ | |
b += 10; | |
cout << "Within PassByValue() \t\tb \t = " << b << endl; | |
} | |
void Reference(int &b){ | |
b += 100; | |
cout << "Within Reference() \t\tb \t = " << b << endl; | |
} | |
void Pointers(int *b){ | |
*b += 1000; | |
cout << "Within Pointers() \t\t*b \t = " << *b << endl; | |
} | |
// Output: | |
// At startup, within main() Bats = 1 | |
// | |
// Within PassByValue() b = 11 | |
// After calling PassByValue(Bats) Bats = 1 | |
// Within PassByValue() b = 11 | |
// After calling PassByValue(rB) Bats = 1 | |
// Within PassByValue() b = 11 | |
// After calling PassByValue(*rB) Bats = 1 | |
// | |
// Within Reference() b = 101 | |
// After calling Reference(Bats) Bats = 101 | |
// Within Reference() b = 201 | |
// After calling Reference(rB) Bats = 201 | |
// Within Reference() b = 301 | |
// After calling Reference(*pB) Bats = 301 | |
// | |
// Within Pointers() *b = 1301 | |
// After calling Pointers(&Bats) Bats = 1301 | |
// Within Pointers() *b = 2301 | |
// After calling Pointers(pB) Bats = 2301 | |
// Within Pointers() *b = 3301 | |
// After calling Pointers(&rB) Bats = 3301 | |
// | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment