In C and C++, one can initialize arrays and structs using braces:
int a[] = {2, 3, 5, 7};
entry e = {"answer", 42};
However, in a talk from 2007, Bjarne mentions that this syntax also works for scalars. I tried it:
int i = {7};
And it actually works! What is the rationale behind allowing the initialization of scalars with braces?
Note: I am specifically not talking about C++11 uniform initialization. This is good old C89 and C++98.
intis POD. So the brace initialization is allowed in case ofint(and for all build-in types), as it makes the initialization-syntax consistent with other PODs.Also, I guess whatever rationale behind C++11 Uniform Initialization Syntax are, are also (partially) applicable to this syntax allowed by C++03. It is just C++03 didn’t extend this to include non-pod types such as the standard containers.
I can see one place where this initialization is helpful in C++03.
Now this can be instantiated with
structwhich begins with a suitable member, as well as any arithmetic type:Also note that POD, whether struct or built-in types, can also be initialized uniformly as:
So I believe one reason is consistency!