I'm trying to understand the reasoning behind the following compilation error (using gcc).
0. struct mystruct {
1. int x;
2. int y;
3. };
4.
5. int foo() {
6. struct mystruct m = {1}; // compiles successfully
7. m = {2,3}; // compilation error: expected expression before ‘{’ token
8. return m.x + m.y;
9. }
However, if I cast the value explicitly in line 7, the code compiles:
5. int foo() {
6. struct mystruct m = {1}; // compiles successfully
7. m = (struct mystruct){2,3}; // compiles successfully
8. return m.x + m.y;
9. }
I'm trying to understand the reasoning behind this error.
Line 6 compiles successfully without raising an error - the compiler figured out automatically the type of m
without the explicit casting. Why doesn't it do the same in line 7?
Thanks
The reasoning is that the C90 syntax allows a compound initializer only.
In other words, the braced thing on the right hand side of the =
is an initializer expression, it's not a literal of the struct
type.
C99 adds compound literals which make it work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With