Search code examples
c++initializationcurly-braceslist-initialization

What is the correct way to initialize a variable in C++


I have the following code :

bool c (a == b);

and

bool c {a == b};

where a and b are some variables of same type.

I want to know that, what is the difference in above two initializations and which one should be preferred in what conditions ? Any kind of help will be appreciated.


Solution

  • Both forms are direct initialization.

    Using curly braces {} for initialization checks for narrowing conversions and generates an error if such a conversion happens. Unlike (). (gcc issues a warning by default and needs -Werror=narrowing compiler option to generate an error when narrowing occurs.)

    Another use of curly braces {} is for uniform initialization: initialize both types with and without constructors using the same syntax, e.g.:

    template<class T, class... Args>
    T create(Args&&... args) {
        T value{std::forward<Args>(args)...}; // <--- uniform initialization + perfect forwarding
        return value;
    }
    
    struct X { int a, b; };
    struct Y { Y(int, int, int); };
    
    int main() {
        auto x = create<X>(1, 2);    // POD
        auto y = create<Y>(1, 2, 3); // A class with a constructor.
        auto z = create<int>(1);     // built-in type
    }
    

    The only drawback of using curly braces {} for initialization is its interaction with auto keyword. auto deduces {} as std::initializer_list, which is a known issue, see "Auto and braced-init-lists".