Why this LOC is valid <int something = {42};>

M

MJ_India

C++ file with following code compiles without any complaint on GCC and
Microsoft Visual C++.

int main() {
int something = {42}; // 1. LOC that makes me sick
// something = something; // To silent unused variable warning
}

{...} seems perfect for initialization for a structure or an array.
My question is; why is it valid to initialize an int with {42}?
Sometimes I think it is okay, but some other time this is confusing.
Please help.

Microsoft Visual C++ also compiles the following lines without any
complaints:
2. int weird[2] = {{{12}}};
3. int weirder = { { 3,} ,};
 
V

Victor Bazarov

C++ file with following code compiles without any complaint on GCC and
Microsoft Visual C++.

int main() {
int something = {42}; // 1. LOC that makes me sick
// something = something; // To silent unused variable warning
}

{...} seems perfect for initialization for a structure or an array.
My question is; why is it valid to initialize an int with {42}?
Sometimes I think it is okay, but some other time this is confusing.
Please help.

Microsoft Visual C++ also compiles the following lines without any
complaints:
2. int weird[2] = {{{12}}};
3. int weirder = { { 3,} ,};

I think the curly braces are optional when writing the initialization of
a scalar variable. Commas are optional in some cases, but I am not sure
they are allowed in initializers; can simply be VC++ extension.

V
 
J

Jorgen Grahn

C++ file with following code compiles without any complaint on GCC and
Microsoft Visual C++.

int main() {
int something = {42}; // 1. LOC that makes me sick
// something = something; // To silent unused variable warning
}

Confirmed, with g++ and full warnings enabled. It must be standard C
and C++. That was news to me too, after ~20 years of C and C++
programming.

And yes, it makes me a bit sick too. On the other hand I have never
seen it cause any confusion in practice.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top