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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With