Aayush Neupane
Aayush Neupane

Reputation: 1246

C++ pass by reference and temporary variables

Is temporary variable created in program below??

void swapr(int & a, int & b)  // use references 
{ 
    int temp;
    temp = a;      // use a, b for values of variables 
    a = b; 
    b = temp;
} 
long a = 3, b = 5; 
swapr(a, b);

in the above code what difference does it make if i use const reference instead? it is said that it creates temporary variable which is swapped instead of actual variable..

if above code cant perform swapping? what is the right code to perform swapping using same data and also using pass by reference?

Upvotes: 2

Views: 2167

Answers (2)

Amal K
Amal K

Reputation: 4874

This will perform the swapping except for the fact that your function accepts integers and you are trying to swap long variables. If your long value exceeds max integer size, it will result in an overflow. So define a separate function for long values.

A reference variable (defined as: int& var;)means a variable that refers to the same variable as another variable. So any change in one variable will also reflect the other variable. So your swapping will also affect the actual argument values.

There are two reasons you define a function parameters as reference variables. One like your case where you want the actual variables to be modified. Second is to prevent the copying overhead. So:

void func(int& a, int& b);

Will pass your arguments as reference, so a and b will refer to the same variables. But:

void func(int a, int b);

Will copy the values of your variables to a and b which is more time consuming.

Now,

const& var Here the variable is not only passed as reference but also it ensures that the function can't modify the original variable. const variables cannot be changed. So if you include const in your function parameter list like this:

void rswap(const int& a, const int& b);

you will get an error because you are trying to modify a and b that is swap them. const is used for protection when passing variables as reference so that they don't accidentally get modified in the function. Usually useful when you just want to print the values or use the values without modifying them.

Upvotes: 1

Oblivion
Oblivion

Reputation: 7374

Compiler will reject your code if you use const reference in your function.

By const you promise to not to modify the variable.

Upvotes: 2

Related Questions