Search code examples
c++initdefault-constructorbracesuniform-initialization

Meaning of default init and value init?


I am very confused by c++ ways of initializing variables. What is the difference if any, between these:

int i; // does this make i uninitialized?
int i{}; // does this make i = 0?
std::array<int, 3> a; // is a all zeros or all uninitialized?
std::array<int, 3> a{}; // same as above?

Thanks for clarifying


Solution

  • int i; // does this make i uninitialized?
    

    Yes, if in local scope and not in global scope.

    int i{}; // does this make i = 0?
    

    Yes, always.

    std::array<int, 3> a; // is a all zeros or all uninitialized?
    

    Uninitialized if in a local scope, but zeroed of in global scope, i.e., same as your first question.

    std::array<int, 3> a{}; // same as above?
    

    All values are default initizlized, i.e., all three elements are zeroed.