This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different.
For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks.
Does anybody know why?
#include <iostream>
using namespace std;
int main()
{
int n, sum, a;
a = 0;
sum = 0;
cin >> n;
while (n>0)
{
a = n % 10;
sum = sum * 10 + a;
n = n / 10;
}
cout << sum;
return 0;
}
2
Answers
the above expression only initializes the last variable ‘a’, leaving ‘n’ and ‘sum’ uninitialized.
although n is assigned a value in
the variable ‘sum’ is likely to have a garbage value. That explains the different results.
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet:
A few general things to keep in mind:
using namespace std;
. That’s a bad practice. See Why is "using namespace std;" considered bad practice?.remainder
inside the scope of thewhile
loop because it was not being used outside the loop.int a
,int n
, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.