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?
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;
In C, you're not allowed to give initial values to elements in struct
s. 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.
上一篇: 单链表主要表达式错误
下一篇: 在结构定义中''''标记之前预期''