Created
July 7, 2016 06:47
-
-
Save mesbahamin/1b4e392a4e51e0d4e3fb20bdd4857406 to your computer and use it in GitHub Desktop.
Example of passing parameters by value and by reference
This file contains hidden or 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; | |
| // These are the function prototypes | |
| int addTenByValue(int num); | |
| int addTenByReference(int &num); | |
| void addTenNoReturn(int &num); | |
| int main() | |
| { | |
| int mynum = 10; | |
| int num_plus_ten; | |
| // Pass the value of mynum, but not mynum itself. | |
| // Only the value is changed, then assigned to num_plus_ten, | |
| // but mynum is unchanged | |
| num_plus_ten = addTenByValue(mynum); | |
| cout << "Value of num_plus_ten: " << num_plus_ten << endl; | |
| cout << "Value of mynum: " << mynum << endl; | |
| // Pass a reference to mynum. mynum itself is changed. | |
| num_plus_ten = addTenByReference(mynum); | |
| cout << "Value of num_plus_ten: " << num_plus_ten << endl; | |
| cout << "Value of mynum: " << mynum << endl; | |
| // Pass a reference to mynum. mynum itself is changed in place. | |
| addTenNoReturn(mynum); | |
| cout << "Value of num_plus_ten: " << num_plus_ten << endl; | |
| cout << "Value of mynum: " << mynum << endl; | |
| system("pause"); | |
| return 0; | |
| } | |
| // These are the function definitions | |
| int addTenByValue(int num) | |
| { | |
| num = num + 10; | |
| return num; | |
| } | |
| int addTenByReference(int &num) | |
| { | |
| num = num + 10; | |
| return num; | |
| } | |
| // Void functions don't return anything. The only way they can | |
| // change a variable is if it's passed to them by reference. This | |
| // is very useful when you want a function to change many variables, | |
| // since functions can only return one thing. | |
| void addTenNoReturn(int &num) | |
| { | |
| num = num + 10; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment