Here is a simple code that takes counter as a reference passed argument and then prints it:
#include <iostream>
using namespace std;
void Fun(int &counter, int n)
{
if(n==0)
return;
Fun(counter+1,n--);
}
int main() {
int counter = 0;
int n = 5;
Fun(counter,n);
cout<<counter<<endl;
return 0;
}
I'm getting this error.
prog.cpp: In function ‘void Fun(int&, int)’:
prog.cpp:7:16: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
Fun(counter+1,n);
^
prog.cpp:3:6: note: initializing argument 1 of ‘void Fun(int&, int)’
void Fun(int &counter, int n)
^
Can somebody please help, why this error?
In Fun(counter+1,n--);
you are not passing counter
to the function. You create a temporary from counter+1
that you pass to the function. To extend the life of a temporary taken by reference, it needs to be const
, so void Fun(const int &counter, int n)
would be compileable.
Counter will however be 0
when the function ends since you never change counter
and the function will never return since you do not decrease the n
you pass to the function. You call the function with n
and then decrease n
.
An alternative:
void Fun(int &counter, int n)
{
if(n==0)
return;
Fun(counter += 1, n - 1); // or Fun(++counter, --n);
}
Both counter += 1
and ++counter
return a reference to counter
which is why this works.
counter++
and n--
will however not work, because the post-increment operators return temporaries too, like in:
int old = n;
n = n - 1;
return old;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.