Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - filling struct after initialization - compilation error

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

like image 540
Oren Avatar asked Mar 19 '23 09:03

Oren


1 Answers

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.

like image 123
unwind Avatar answered Mar 23 '23 12:03

unwind