stackoverflow1453

Programming&&Games&&Life

Archive for Cplusplus

Passing arguments by Value, Reference, Address

PASSING ARGUMENTS BY VALUE

** When arguments are passed by value, a copy of the argument is passed to the function.
** Because a copy of the argument is passed to the function, the original argument can not be modified by the function.
** The only way to return a value back to the caller is via the function’s return value.

void foo(int y)
        {
            using namespace std;
            cout << "y = " << y << endl;
        }
         
        int main()
        {
            foo(5); // first call
         
            int x = 6;
            foo(x); // second call
            foo(x+1); // third call
         
            return 0;
        }

OUTPUT:
y = 5
y = 6
y = 7

PASSING ARGUMENTS BY REFERENCE

**One way to allow functions to modify the value of argument is by using pass by reference.
**In pass by reference, we declare the function parameters as references rather than normal variables.

      void foo(int &y) // y is now a reference
      {
          using namespace std;
          cout << "y = " << y << endl;
          y = 6;
          cout << "y = " << y << endl;
      } // y is destroyed here
       
      int main()
      {
          int x = 5;
          cout << "x = " << x << endl;
          foo(x);
          cout << "x = " << x << endl;
          return 0;
      }

OUTPUT:
x = 5
y = 5
y = 6
x = 6

PASSING ARGUMENTS BY ADDRESS

**There is one more way to pass variables to functions, and that is by address.
**Passing an argument by address involves passing the address of the argument variable
rather than the argument variable itself.
**Because the argument is an address, the function parameter must be a pointer.
**The function can then dereference the pointer to access or change the value being pointed to.

Here is an example of a function that takes a parameter passed by address:

void foo(int *pValue)
{
    *pValue = 6;
}
 
int main()
{
    int nValue = 5;
 
    cout << "nValue = " << nValue << endl;
    foo(&nValue);
    cout << "nValue = " << nValue << endl;
    return 0;
}

OUTPUT:

nValue = 5
nValue = 6