mercredi 30 mars 2016

What is the difference between initializing with = and initializing with {}?

You can initialize a variable using = . For example:

int a = 1000;

C++ 11 introduced an extra notation {} . For example:

int a {1000};

According to Programming: Principles and Practices by Bjarne Stroustrup:

C++11 introduced an initialization notation that outlaws narrowing conversions.

I wanted to check out this cool feature. And I typed a piece of code twice:

#include "std_lib_facilities.h"     |     #include "std_lib_facilities.h" 
                                    |
int main()                          |     int main()
                                    |
{                                   |     {
    int x = 254;                    |         int x {254};
    char y = x;                     |         char y {x};
    int z = y;                      |         int z {y};
                                    |
    cout << "x = " << x << '\n'     |         cout << "x = " << x << '\n'
         << "y = " << y << '\n'     |              << "y = " << y << '\n'
         << "z = " << z << '\n';    |              << "z = " << z << '\n';
                                    |
}                                   |     }

The code on the left uses = whereas the code on the right uses {}

But the code on the right hand side loses some information even after using {}. Thus the output is same in both pieces of code:

x = 254

y = ■

z = -2

So, what's the difference between initializing with = and initializing with {} ?

Aucun commentaire:

Enregistrer un commentaire