tags:

views:

392

answers:

8

Hi,

I am asking one basic question about the initialization. My understanding is that the int will be initialized to 0 automatically. However, it's not. The code below print random value. Can anybody tell me the rule of initialization? Under what condition, the variable will be initialized automatically?

int main () {

int a[10];
int i;

cout<<i<<endl;
for(int i = 0; i< 10  ; i++)
 cout<<a[i]<<" ";

 return 0;
}
+4  A: 

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).

Vivin Paliath
+1  A: 

Local variables aren't initialized unless you do it yourself. What you're seeing is whatever garbage was on the stack before your method was called.

Anon.
+2  A: 

This post says it best: http://www.velocityreviews.com/forums/showpost.php?p=1528247&amp;postcount=10

There's no "default" constructor for non-class types, but there is default (zero) initialization. Unfortunately, for braindead compatibility with C, the default initialization is NOT done for POD types in the following circumstances:

Naked (i.e., declared without initializers) variables local to a class or function.

dynamically allocated instances.

However, in other places (notably static variables) and in the case of anything given the empty initializer paramters (when that is valid), gets the default (zero) initialization.

Will
I wouldn't say it's due to "brainded compability with C", I think it has more to do with C++'s "don't pay for what you don't use" philosophy.
Manuel
+8  A: 

It will be automatically initialized if

  • it's a class/struct instance which you construct, like MyClass instance; (in general: any non-POD type)
  • you use array initializer syntax, e.g. int a[10] = {} (all zeroed) or int a[10] = {1,2}; (all zeroed except first and second)
  • 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++.

AndiDog
The first point is a bit inaccurate. It'll be automatically initialized if it is a non-POD type. :)
jalf
Right, changed that ;) thx
AndiDog
Variables with static storage duration of "plain type" are also initialized to zero (or a null pointer, in the case of pointers). This would be either something declared `static` inside a function, or something declared at namespace scope (i.e. outside any function).
Jerry Coffin
+2  A: 

In C++, automatic variables are undefined until they are explicitly given a value. Perhaps you are thinking of C# or other .Net languages, or Java.

calmh
+3  A: 

See section 4.9.5 Initialization of The C++ Programming Language.

Depending on whether your variable is local, static, user-defined or const default initialization can happen.

Because you're using POD (Plain Old Datatypes), the auto variable is not initialized to any default value.

Nick Presta
+2  A: 

To force initialization of a POD (which int is), you can use copy initializer syntax:

#include <iostream>

int main() {
  int i = int();
  int j;

  std::cout << "i: " << i << std::endl;
  // warning: undefined behavior
  std::cout << "j: " << j << std::endl;
}

This is falls under "only pay for what you use". If you are going to subsequently assign a value to the variable, or possibly not use it at all, there's no reason to do the work of initializing it. To get that, you have to explicitly ask that that work be done.

Logan Capaldo
this does not work for `unsigned int`s or `long long` or similar types which consist of more than one word in GCC, however it does work in MSVC, related question: http://stackoverflow.com/questions/2144012/explicit-type-conversion-and-multiple-simple-type-specifiers
smerlin
A: 

Although your recent discovery may be unwelcome (because you may need to initialise some variables other languages would have taken care of), it can mean fewer cpu cycles, and thus faster code.

phlip