0

I'm trying to learn C++, specifically how to declare and initialize variables. I wrote this code, and I don't know why the variable c is giving a value that I have not assigned it yet.

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!\n";

    int a, b;
    a = 1;
    b = 2;
    int d(4);
    int result;
    auto num = b;
    decltype(b) c;

    result = a + b - d;
    cout << c;
}

The output is -2, but I didn't state c = -2 anywhere!

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Terry Qu
  • 1
  • 2

2 Answers2

1

If you have not initialized the variable, it contains garbage value.

Ram
  • 1,225
  • 2
  • 24
  • 48
1

In C/C++, the values declared within a function represent some bytes of main memory on the cpu stack. Those bytes are usually dirty and need initialization. If you don't the values are undefined. That you're always getting '-2' is merely coincidence.

Arne J
  • 415
  • 2
  • 9
  • Why doesn't the program just say that the uninitialized variable is undefined? That's what happens in another language like python. Also, does initializing a variable mean giving a value through c = 1 or something? – Terry Qu Sep 27 '19 at 04:45
  • @TerryQu Most compilers will warn you about initialized variable usage with the proper warning flags. They are very different languages, Python can have an "uninitialized" state due to its dynamically-typed nature. Yes. – kmdreko Sep 27 '19 at 05:07