888 888 - 1 month ago 7
C++ Question

Reverse number function not working properly after first run

Here is my code:

#include <iostream>
using namespace std;

int rev(int i) {
int ret;
while (i >= 1) {
ret += i%10;
i /= 10;
ret *= 10;
}
return ret/10;
}

int main() {

//rev(4);
cout << rev(123) << endl;

return 0;
}


When I run it, I get "321", as I should.

But when I un-comment the line above it, I get "4321"!

Why is this?

Answer

The initial value of int ret; is undefined (any value). Replace it with int ret = 0;.

Comments