Reputation: 141
I have a struct like this:
struct foobar {
int i;
char *word;
};
I know this will work:
struct foobar {
int i;
char *word;
};
struct foobar three = {3, "three"};
Why doesn't the following work though?
struct foobar {
int i;
char *word;
} three;
three = {3, "three"};
It will give the error: expected expression before ‘{’ token
.
Upvotes: 13
Views: 19303
Reputation: 352
It looks like you are trying to use the so-called "instantiation syntax" here. Unfortunately, this only works at the very moment you declare the variable!
If you do it after declaration (like in your example), you have to use one of the more cumbersome ways.
To clarify, this is how it would work:
struct foobar {
int i;
char *word;
} three = {3, "three"};
Upvotes: 1
Reputation: 450
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.
Upvotes: 20
Reputation: 50
The reason why this:
struct foobar {
int i;
char *word;
} three;
three = {3, "three"};
doesn't work is because you did not typedef the struct.
You want to do:
typedef struct foobar {
int i;
char *word;
} three;
Once you typedef, three now becomes your new datatype like int or char. If you want to work with three you want to do this:
three x = {3, "three"};
You initialize a variable, such as x, and assign it {3, "three"}
Upvotes: -3
Reputation: 35154
"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++.
Upvotes: 11