Warning final_number may be uninitialized i this function.

i tried to make a program that reads binary but the output is "1" at all times... why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
using namespace std;

int main()
{
    int stop = 0;
    int input, last_number, final_number;
    
    cout << "type a 0 or 1 to input the binary number. type 2 to compile\n";
    cin >> input;
    if(input == 1){
        final_number++;
        }
        last_number = 1;
 while (stop == 0){
     cin >> input;
     if(input < 3){
      
      last_number = (last_number * 2);
      if(input == 1){
         final_number + last_number;
          }
          if (input == 2){
              stop = 1;
              }
     }
     else{
         cout << "Invalid number try again. type 2 to compile\n";
         }
    }
    cout << final_number;
}
Last edited on
I only looked at it for about 5 seconds, but your line 21 isn't doing anything.
final_number + last_number; // nothing is assigned here. Nothing changes
So that's probably where your bug is.

Edit: You also never initialize final_number to a value. It's a garbage value that's getting incremented.

You should also take a moment and look at your indentation. It's misleading as it stands right now. I suggest going through your code, line by line, operation by operation, and explain to yourself, out-loud, what is happening in the program. Talk to a rubber duck if necessary.
https://en.wikipedia.org/wiki/Rubber_duck_debugging
Last edited on
Thanks i fixed it by typing
final number = (final_number + last_number);
intead of
final_number + last_number;
Last edited on
Topic archived. No new replies allowed.