P
P
Pro100Vova56262020-05-04 18:28:55
C++ / C#
Pro100Vova5626, 2020-05-04 18:28:55

Is an uninitialized local variable used?

A binary number is entered into the program, a decimal number is displayed

#include <iostream>

using namespace std;

int main() {

  setlocale(LC_CTYPE, "Russian");	// добавляет русский язык в консольное приложение

  
    int num, r, a, b = 0;
    cout << "Введите число в двоичной системе:  ";
    cin >> num;

    while (num != 0) {
      a = num % 10;
      if (b == 0)
        b = 1;
      if (b != 0)
        a *= b;
      r += a;
      b *= 2;
    }
    cout << "Число в десятичной системе = ", r;
  return 0;
}


It throws an error: "An uninitialized local variable 'r' has been used". Only for variable "r". For other variables, no errors are shown.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2020-05-04
@Pro100Vova5626

What's the question?
Yes, an uninitialized variable r is used.
When you declare a variable inside a function (automatic) without an initializer, then its real value is not defined, i.e. it can be anything. Any garbage that is left in memory at the location of the variable will become the value of the variable.
And then you do r += a; Those. you stack a with garbage. What do you want to get as a result?
Just initialize r to zero, just like you did for b.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question