0

I saw a initialization syntax which is new for me. I searched on google and here but I couldn't find something useful.

int a = 0;
int a = {0};
int a{0}; // <- this is new for me    

Why do I need third style while others exist? What is the difference between each exactly?

Thanks.

Mehmet Fide
  • 1,643
  • 1
  • 20
  • 35
  • 2
    The third one solves what Scott Meyers called "C++'s most vexing parse." Under certain circumstances, `int a(var)` could be misinterpreted as a function declaration rather than constructing a variable. http://en.wikipedia.org/wiki/Most_vexing_parse – Joe Z Dec 05 '13 at 06:00

2 Answers2

4

You may be interested by C++11 initializer lists. They might not explain the third example, but they are useful, especially for real class objects.

Your code int a{0}; is called uniform initialization in C++11. See also most vexing parse wikipage (as commented by Joe Z).

Take time to at least read the C++11 wikipage. The new features of C++11 makes it almost a different language than C++03.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

This form of initialization is referred to as list initialization in C++11.

When used with variables of built-in type, list initialization is different in one way: you can't list initialize variables of built-in type if the initializer might lead to the loss of information.

double pi = 3.1415926;
int a(pi); //fine
int a{pi}; //compile error
Yu Hao
  • 119,891
  • 44
  • 235
  • 294