Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment operator on reference variable

Tags:

c++

Why does pre-increment work but post-increment does not on a reference variable?

#include <iostream>

void swap(int&, int&);

int main()
{
    int x=10, y=20;
    int &a=x, &b=y;
    swap(++a, ++b);  //swap (a++,b++) is not allowed.
    printf("%d %d ", a, b);
    return 0;
}

void swap(int& x, int& y)
{
    x+=2;
    y+=3;
} 

Why is swap(++a, ++b) allowed but swap(a++, b++) says:

[Error] invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'

like image 526
renukar Avatar asked Oct 02 '15 16:10

renukar


1 Answers

When you call

swap (a++,b++)

a++ and b++ give you a temporary object since post incrementing returns the previous values. Since swap() takes its parameters by reference they cannot bind to those temporary values. using ++a and ++b work as we first increment a and b and then pass it to swap so there is no temporary.

like image 171
NathanOliver Avatar answered Dec 31 '22 01:12

NathanOliver