Return to Examples

C++ Programs:
Pass-By-Value: 

# include <iostream.h>
int sub(int);       //Function prototype

main()
{
  int function_value;
  int x = 99;
  cout << "x before call: "<< x << endl;
  function_value = sub(x);     //Call function
  cout << "x after call: "<< x << endl;
  cout << "The value returned from function is "
       << function_value <<endl;
}

// Definition of Function
int sub(int a)
 {
   a = a * 10;
   return a;
 }

The output will be
x before call: 99
x after call: 99
The value returned from function is 990
Pass-By-Reference:
# include <iostream.h>
int sub(int &);       //Function prototype

main()
{
  int function_value;
  int x = 99;
  cout << "x before call: "<< x << endl;
  function_value = sub(x);     //Call function
  cout << "x after call: "<< x << endl;
  cout << "The value returned from function is "
       << function_value <<endl;
}

// Definition of Function
int sub(int &a)
 {
   a = a * 10;
   return a;
 }

The output will be
x before call: 99
x after call: 990
The value returned from function is 990
Pass-By-Pointers:
# include <iostream.h>
int sub(int *);       //Function prototype

main()
{
  int function_value;
  int x = 99;
  cout << "x before call: "<< x << endl;
  function_value = sub(&x);     //Call function
  cout << "x after call: "<< x << endl;
  cout << "The value returned from function is "
       << function_value <<endl;
}

// Definition of Function
int sub(int * a)
 {
   *a = *a * 10;
   return *a;
 }

The output will be
x before call: 99
x after call: 990
The value returned from function is 990
Note:  Pass-By-Reference and Pass-By-Pointer get the same output.