Heman Gandhi
Heman Gandhi

Reputation: 1371

C initialize struct in switch case

So I have the following "shape" in my code:

mystruct t;
switch(something){
    case THIS:
        t = {/*initialization*/};
        break;
    case THAT:
        t = {/*initialization*/};
        break;           
    case AND_THE_OTHER:
        t = {/*initialization*/};
        break;
}

gcc insists that there should be an expression before the {:

error: expected expression before '{' token
    t = {
        ^

Why? What does gcc think I'm up to? What's the clean way to do this?

Upvotes: 1

Views: 711

Answers (2)

cadaniluk
cadaniluk

Reputation: 15229

Use compound literals:

t = (mystruct) { ... };

This is supported by C99+, but supported as an extension by GCC for C90.

Upvotes: 3

dbush
dbush

Reputation: 224532

What you're doing is assignment, not initialization. Initialization can only be performed at the time the variable is defined. Curly braces may be used to initialize a variable, but not to assign.

You'll need to assign each member of the struct individually.

Upvotes: 2

Related Questions