-1
#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    
    cout<<a<<endl;
    cout<<b;

}

Why b has 16 value when i compile this? I cant understand why b has 16 not 0. Int doesnt have 0 as default value?

lolorek
  • 17
  • 5
  • define variable in c++ without initialize in future it will give undefined value. – N0ll_Boy May 28 '21 at 07:59
  • You have stumbled upon something super important, and not to forget in the future. When you declare a variable, its value is basically random. This is why you should always initialise a variable before using its value. –  May 28 '21 at 08:01
  • @N0ll_Boy the behavior is undefined, which is different from having undefined values. For example on some architectures like Itanium, accessing an uninitialized variable will give you a segfault – phuclv May 28 '21 at 08:20

1 Answers1

4

Absolutely not. C++ does not initialise variables unless you ask it to. (Setting a variable to 0 for example is at least one instruction: typically reg XOR reg. That could be wasteful.) The behaviour of reading an uninitialised int is undefined.

(Note you can do some things with uninitialised variables, such as setting a pointer or reference to one, computing sizeof(a), and using decltype(a). But passing it by value to a function is undefined behaviour. That often trips up even professional programmers.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483