Why do I have to assign a {} expression to an object?

I'm playing around the bracket list expression, and I got an error
error: expected ‘;’ before ‘}’ token
when running this:

1
2
3
4
int main() {
    {1,2,3};
    return 0;
}


Why?
Last edited on
{1,2,3} isnt anything in c++. it probably would actually compile with a ; after the 3, but it wouldn't do anything even if you 'fixed' it.
this is something:
int x{3}; //the compiler can read that x is an integer that will have the value 3.
this is something too:
int x[] = {1,2,3}; //x is an array of int, and it will have 3 locations with 1,2,3 in them.

I guess 'an' answer is that your syntax is wrong and the 'why' is that the compiler does not understand what you want it to do. The language requires you to follow its rules so that it can understand what you want done.

due to legacy of an old language a lot of silly things WILL compile that do nothing or serve no purpose, but your example isn't one of them :)
Last edited on
Why do I have to assign a {} expression to an object?

What you're referring to is list-initialization.
https://en.cppreference.com/w/cpp/language/list_initialization

The compiler seems to think you wanted a compound statement containing the expression statement 1, 2, 3;, where the 1, 2, 3 is a pointless usage of the built-in comma.
Last edited on
And in case you're specifically after a legalese type of answer, the standard says that "a braced-init-list may appear on the right-hand side of
- an assignment to a scalar [with some qualifications]
- an assignment to an object [...]."

So I believe that implies that any braced-init-list that doesn't match that pattern may not appear, and therefore cannot be a braced-init-list.
Last edited on
Topic archived. No new replies allowed.