I am making a program that prints a number requested to the user, in reverse. For example if it is 16, it will return 61 or if it is 1020, it will return 0201. It turns out that when I compile the program in P1++ it gives me these errors:
program.cc: In function ‘int main()’:
program.cc:22:21: error: ‘unit’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
22 | reversed_number += unit;
| ~~~~~~~~~~~~~~~~^~~~~~~
program.cc:18:24: error: ‘number_with_zeros’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
18 | reversed_number += number_with_zeros;
| ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
cc1plus: all warnings being treated as errors
and in g++ it compiles for me but if I insert 16 it returns 121.
The code is as follows: (I try to use only the most basic structures to do it).
#include <iostream>
using namespace std;
int main() {
int number;
cin >> number;
int selection_number_division = number;
int multiplication_division = number;
int reversed_number = 0;
int number_with_zeros, unit;
while (selection_number_division > 0) {
multiplication_division = selection_number_division % 10;
for (int i = 10; i <= selection_number_division; i *= 10) {
number_with_zeros = multiplication_division * i;
}
reversed_number += number_with_zeros;
unit = selection_number_division % 10;
selection_number_division /= 10;
}
reversed_number += unit;
cout << reversed_number << endl;
}
I have tried to simplify your code to make it a bit more readable. I also changed the name of the variables, since they are very long and at first glance I couldn't understand the logic and where the problem was. You could do it like this:
Output: