Cpp - Reference and Function

Introduction

In C++, passing by reference is accomplished in two ways: using pointers and using references.

Passing an object by reference enables the function to change the object being referred to.

swap() with Pointers

When you pass in a pointer, you pass in the actual address of the object.

Thus, the function can manipulate the value at that address.

To make swap() change the actual values using pointers, the function should be declared to accept two int pointers.

Then, by dereferencing the pointers, the values of x and y will be swapped.

Demo

#include <iostream> 
   //  w  w w. j  ava 2 s  .  com
void swap(int *x, int *y); 
 
int main() 
{ 
    int x = 5, y = 10; 
   
    std::cout << "Main. Before swap, x: " << x  
                  << " y: " << y << std::endl; 
    swap(&x, &y); 
    std::cout << "Main. After swap, x: " << x  
                  << " y: " << y << std::endl; 
    return 0; 
} 
   
void swap(int *px, int *py) 
{ 
    int temp; 
   
    std::cout << "Swap. Before swap, *px: " << *px  
                  << " *py: " << *py << std::endl; 
   
    temp = *px; 
    *px = *py; 
    *py = temp; 
   
    std::cout << "Swap. After swap, *px: " << *px  
                  << " *py: " << *py << std::endl; 
}

Result

swap() with References

The parameters are declared to be references, the semantics are passed by reference.

Demo

#include <iostream> 
 
void swap(int &x, int &y); 
 
int main() /*from  w w  w  . j  av  a2 s . com*/
{ 
    int x = 5, y = 10; 
 
    std::cout << "Main. Before swap, x: " << x  
                  << " y: " << y << std::endl; 
    swap(x, y); 
    std::cout << "Main. After swap, x: " << x  
                  << " y: " << y << std::endl; 
    return 0; 
} 
   
void swap(int &rx, int &ry) 
{ 
    int temp; 
   
    std::cout << "Swap. Before swap, rx: " << rx  
                  << " ry: " << ry << std::endl; 
   
    temp = rx; 
    rx = ry; 
    ry = temp; 
   
    std::cout << "Swap. After swap, rx: " << rx  
                  << " ry: " << ry << std::endl; 
}

Result

Related Topics

Exercise