I am new to C++ and i am trying to create a recursive function that lists each individual digit in an integer and then provides the sum of those digits and ‘sum’ must be a variable that is passed to the function by reference.
I keep getting the error that "invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'" and i think i understand what the error is telling me basically that i am passing a constant number by reference which doesnt work, I just cant figure out how to fix it. Any advice would be appreciated. This is what i got so far.
prog.cpp:14:33: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
return digits (n/10);
^
prog.cpp:4:5: error: in passing argument 1 of ‘int digits(int&, int)’
int digits(int& sum, int n) {
^
int digits(int& sum, int n)
The digits function takes two parameters but you're only sending one. And n/10 is an expression that evaluates to a value to be sent. I don't think it has a memory address that the digits function can reference.
return digits (n/10);
Edit: s doesn't get initialized before you send it to the digits function in main.