-4
#include <iostream>
using namespace std;
int main()
{
    int d=4,r;
    d=r+5;
    cout<<d;
    return 0;
}

The r variable has not a value .

How the compiler build this program?!

The output is : 21

Strive Sun
  • 5,988
  • 1
  • 9
  • 26
qlfxmd
  • 1
  • 1

3 Answers3

1

The variable r has no value assigned. This is called "uninitialized".

Accessing the value of such a variable is undefined behavior.

What that means is that anything can happen. It is not defined what should happen. A compiler that would display an animation of a pink unicorn dancing on the moon would be just as standard compliant as one that terminates your program.

For practical reasons, most compilers just use whatever value was at the position in memory when the variable was created.

Some compilers fill all variables with a default value when started at debug configuration, so you know that this value means "uninitialized" when you see it.

What you specific compiler did is something you could figure out, but the better use of time would be to write a program that only uses well defined behavior from the start.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
-1

Variables in C++ aren't default-initialized. That means that when you declare a variable (of primitive type) the compiler just allocates the memory for the variable but doesn't actually do anything to the value stored at that place. So your r variable is 16 because that's just what was stored at that address before you declared the variable.

Note: For objects, the default constructor is called:

class C {
public:
  C() { /* DO STUFF */ }
};

// ...

C c; // <-- C::C() is called.

Nikita Demodov
  • 553
  • 5
  • 17
-1

Since r is not initialized, some garbage value is assigned to it. It could be assigned to anything. In your case, it seems to be assigned to 16.

Hammad Ali
  • 168
  • 11