whiskey golf
whiskey golf

Reputation: 177

Expected ' ' before '=' token in struct definition

I have a struct I am making for a case to model a simple semaphore, the code is as follows

struct semaphore{
    int count = 1;
    struct PCB *Sem_Queue;
};

When I try to compile I get the error

Expected ':', ',' etc before '=' token int count = 1;

Can anyone point out to me why this error is occurring?

Upvotes: 3

Views: 909

Answers (2)

Jonathan Lam
Jonathan Lam

Reputation: 17351

I assume you are trying to set a default value for a field in a struct definition.

You cannot do this.

You have to declare the count field like you did with PCB: with only a type and a name, like so:

int count;

Upvotes: 4

templatetypedef
templatetypedef

Reputation: 372784

In C, you're not allowed to give initial values to elements in structs. If you'd like to create a semaphore struct where every new semaphore's count field is set to 1, you can do so by creating a helper function like

 struct semaphore* semaphore_new()

that returns a newly-allocated semaphore* and sets the count field before returning it.

Upvotes: 5

Related Questions