c++ reference to function code example

Example 1: reference function in c++

// function definition to swap the values.
void swap(int &x, int &y) {
   int temp;
   temp = x; /* save the value at address x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
  
   return;
}

Example 2: calling by reference c++

void fun2(int& a) 
{
    a = 5;
}

int main()
{
    int b = 10;
    fun2(b); 

    // now b = 5;
    return 0;
}

Example 3: calling by reference c++

void fun3(int a)
{
    a = 10;
}

int main()
{
    int b = 1;
    fun3(b);
    // b  is still 1 now!
    return 0;   
}

Example 4: reference function in c++

#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values using variable reference.*/
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}

Tags:

Cpp Example