Variable initialization in C++

int doesn't initialize to zero. When you say int i;, all you're doing is reserving space for an integer. The value at that location is not initialized. That's only done with you say int i = 0; (or int i = 5; in which case the value is initialized to 5). Eitherway, it's good practice to initialize a variable to some known value. Otherwise, i holds whatever random value was at that memory location when space was reserved for it. This is why the cout prints out a random value.

Default values depend on the implementation of the language. Some languages will initialize it to some "sane" value (like 0 perhaps). As a rule of thumb, I always initialize a variable to some sensible value (unless I know that I am going to initialize it to something else for sure before I use it). As I mentioned before, it's unwise to assume that the value is going to be something sane. It may or may not be (depending on the language, or the implementation of the interpreter/compiler for that language).


It will be automatically initialized if

  • it's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance;
  • you use array initializer syntax, e.g. int a[10] = {} (all zeroed) or int a[10] = {1,2}; (all zeroed except the first two items: a[0] == 1 and a[1] == 2)
  • same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here)
  • it's a global/extern variable
  • the variable is defined static (no matter if inside a function or in global/namespace scope) - thanks Jerry

Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.