C++ Function Arguments Passing: Passing by Reference

Introduction

When a function parameter type is a reference type, then the actual argument is passed to the function.

The function can modify the value of the argument.

Example:

#include <iostream> 

void myfunction(int& byreference) 
{ 
    byreference++; // we can modify the value of the argument 
    std::cout << "Argument passed by reference: " << byreference; 
} 

int main() /*from w ww  . j av  a 2  s  .  c om*/
{ 
    int x = 123; 
    myfunction(x); 
} 

Here we passed an argument of a reference type int&, so the function now works with the actual argument and can change its value.

When passing by reference, we need to pass the variable itself; we can't pass in a literal representing a value.

Passing by reference is best avoided.




PreviousNext

Related