Struct initialization in C with error: expected expression

It doesn't work, because C doesn't know what type {3, "three"} should be of; C doesn't look at the left side of the "=" operator to guess your type, so you don't have any type information there. With C99 you can use a compound literal for this:

three = (struct foobar) { 3, "three" };

The cast gives the type, the values in the curly brackets the initiallizer. The result is than assigned to your variable three.


"initialization" and "assignment", though having quite similar syntax, are two different things with different restrictions.

"Initialization" means to define the initial value of a variable right in the course of variable definition. Assignment, in contrast, assigns a value to a variable defined elsewhere in the program.

C does not support assignment of values to variables of type struct or array, but it supports initialization of variables of these types:

struct foobar three = {3, "three"} is an initialization, since the value is defined together with the variable definition. This is supported in C and in C++.

struct foobar three; three = {3, "three"} in contrast, is an assignment, because the variable is first declared, but the value is assigned in a separate statement. This is not supported in C, but would be supported in C++.

Tags:

C