Isn’t the value of an unassigned int variable in C++ 0 (zero)?

Asked

Viewed 58 times

4

I’m having my first serious contact with C++.

I wanted to see what would happen if I added up a value int of a variable assigned with another without assigning, and see what happened:

#include <cstdio>

using namespace std;


int main()
{

    int num;
    int num2; // Não atribuido

    num = 10;

    printf("O valor é %d\n", num + num2);

    return 0;
}

The result obtained was:

The value is 134513787

I’m not criticizing the language, but I wanted to understand why the printed value was this, rather than printing "The value is 10", since num2 has no integer assigned.

Is there any explanation why the returned value is this?

  • 1

    @Bacchus The answer to the linked question says that the value should be zero in examples such as this question. The example he gives of memory junk is with struct.

  • I put a second answer to the question nominee, I hope it’s clearer...

  • Thanks @Joséx, now yes I understand how it works.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.