call by reference c++ 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++

int main() {
    int b = 1;
    fun(&b);
    // now b = 10;
    return 0;
}

Example 3: calling by reference c++

void fun(int *a)
{
   *a = 10;
}

Example 4: call by reference c++ example

//call by reference example c++
#include <iostream>

using namespace std;

void swap(int& x, int& y) {
	cout << x << " " << y << endl;
	int temp = x;
	x = y;
	y = temp;
	cout << x << " " << y << endl;

}

int main() {
    
	int a = 7;
	int b = 9;

	swap(a, b);

}

Example 5: calling by reference c++

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

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

    // now b = 5;
    return 0;
}

Example 6: calling by reference c++

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

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

Tags:

Cpp Example