Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //http://pastebin.com/u/TheWhiteFang
- //pass by everything
- //Return by value
- int DoubleValue(int nX)
- {
- int nValue = nX * 2;
- return nValue; // A copy of nValue is returned here
- } // nValue goes out of scope here
- ---------------------------------------------------------------------------------------------------------------------------------//Return by reference
- int& DoubleValue(int nX)
- {
- int nValue = nX * 2;
- return nValue; // return a reference to nValue here
- } // nValue goes out of scope here
- struct FixedArray25 {
- int anValue[25];
- };
- int& Value(FixedArray25 &rArray, int nIndex) {
- return rArray.anValue[nIndex];
- }
- int main() {
- FixedArray25 sMyArray;
- // Set the 10th element of sMyArray to the value 5
- Value(sMyArray, 10) = 5;
- cout << sMyArray.anValue[10] << endl;
- return 0;
- }
- ---------------------------------------------------------------------------------------------------------------------------------//Return by Address
- int* DoubleValue(int nX)
- {
- int nValue = nX * 2;
- return &nValue; // return nValue by address here
- } // nValue goes out of scope here
- int* AllocateArray(int nSize)
- {
- return new int[nSize];
- }
- int main()
- {
- int *pnArray = AllocateArray(25);
- // do stuff with pnArray
- delete[] pnArray;
- return 0;
- }
- ---------------------------------------------------------------------------------------------------------------------------------//more examples
- #include <iostream>
- using namespace std;
- void method1(int *inVal){ //pass by reference
- *inVal = 5;
- };
- void method2(int &inVal){ //pass by address
- inVal = 5;
- };
- int method3(int inVal){ //pass by value
- return 5;
- };
- int main()
- {
- int data1 = 0, data2 = 0, data3 = 0;
- method1(&data1);//pointer needs input address
- method2(data2);//method2 function will change the value in address data2
- data3 = method3(data3);//function passes value to data3
- cout << data1 << endl;
- cout << data2 << endl;
- cout << data3 << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement