Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected ' ' before '=' token in struct definition

Tags:

c

struct

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?

like image 831
whiskey golf Avatar asked May 12 '26 17:05

whiskey golf


1 Answers

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.

like image 105
templatetypedef Avatar answered May 14 '26 09:05

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!