0

I'm very new to C++ and have just started out. I'm doing a simple exercise where I need to declare a variable with type int and add to it.

Essentially the integer has a starting value of 44 and I have no idea why.

The exercise comes out of a book I'm following.

Here is my code:

#include <iostream>
using namespace std;

int main()
{
   int sum;
   sum = sum + 1;
   cout << sum;
   return 0;
}

If I run the following code I get the answer of 45, which makes no sense at all to me.

I want to understand why sum has a value of 44, if no value is assigned to it.

I'm using VScode and the g++ compiler.

Thanks!

  • 1
    You need to write 'int sum = 0;' if you wish to initialise it otherwise it has an undefined value, it could be anything, not just 44. – Mercer Aug 11 '18 at 11:00

1 Answers1

3

You have to initialize variable at first. The correct code would be:

int sum = 0;
sum = sum + 1;

In your case you have undefined behavior.

skap
  • 320
  • 3
  • 16
  • Hello thank you, I know that you would need to do that first, but my assignment that I'm doing wants me to do the code above, I'm just curious as to why it automatically assigns 44 to it. – OliviaRayne Aug 11 '18 at 11:02
  • It's not assigned, it's just what's already at that address in memory. It could be anything. – Mercer Aug 11 '18 at 11:04