Variable initialization in C++

2019-01-01 09:19发布

问题:

My understanding is that an int variable will be initialized to 0 automatically; however, it is not. The code below prints a random value.

int main () 
{   
    int a[10];
    int i;
    cout << i << endl;
    for(int i = 0; i < 10; i++)
        cout << a[i] << \" \";
    return 0;
}
  • What rules, if any, apply to initialization?
  • Specifically, under what conditions are variables initialized automatically?

回答1:

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



回答2:

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



回答3:

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.



回答4:

This post says it best: http://www.velocityreviews.com/forums/showpost.php?p=1528247&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.



回答5:

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.



回答6:

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.



回答7:

Different operating systems ( i.e. OS X vs. Ubuntu Linux ) will react differently to uninitialized versus initialized variables in C++. In my experience, the OS X version of gcc will compile and print out 2 for both versions of the code below. Where as if I\'m working on an Ubuntu Linux machine the first code block will print out whatever happened to be at the memory location the variable references ( + 2 after the loop ).

    int c;

    for( int i = 0; i < 3; i++ )
    {
        c++;
    }

    cout << c << endl; 

Where as, they will all give you the same results for:

    int c = 0;

    for( int i = 0; i < 3; i++ )
    {
        c++;
    }

    cout << c << endl; 


回答8:

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.



回答9:

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value.

Par. 8.5, section 11 of a recent C++0x draft N3092.pdf,

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/



回答10:

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.



回答11:

Here int i; is a automatic variable which must be initialize manually. auto variable doesn\'t initialize automatically in c and c++.

If you want compiler to initialize it, then you need to use following things,

declare i as static variable.

static int i; // zero assign to the i by compiler.

declare i as global variable[outside the main()].