Majid Azimi
Majid Azimi

Reputation: 5745

Can't assign struct variable in header file

I have a header file including a structure like this:

typedef struct
{
    int index = -1;
    stack_node *head;
} stack;

But when compiling with cc it shows error at the assignment line (int index = -1):

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token

should I add an initialization function to initialize variables?

Upvotes: 3

Views: 5431

Answers (4)

lxcid
lxcid

Reputation: 1043

You can't assign a value in struct declaration like that.

stack s = { -1, 0 };

Try this.

Technically, if you are using C++ you can define constructor for struct. I don't think this work for C. Use the above if you are strictly in a C environment.

typedef struct _stack
{
    int index = -1;
    stack_node *head;
    _stack() {
        index = -1;
        head = 0;
    }
} stack;

Something like this. Let me know if it doesn't work cause I writing base on a few memory and haven't write much C for quite a while.

UPDATE: I like @mouviciel answer, I didn't know you could initialize individual member variable by prefixing . in front. Learnt something. Thanks.

Upvotes: 1

mouviciel
mouviciel

Reputation: 67831

What you provide is not a variable declaration but a type definition. You can't assign default values to struct fields in a typedef.

If you want to assign an initial value to a struct variable, you should try:

stack myStack = { .index = 1 };

This works in C99.

Upvotes: 5

Andrey Sboev
Andrey Sboev

Reputation: 7672

typedef struct
{
    int index;
    stack_node *head;
} stack;

stack getStack()
{
    stack st;
    st.index = -1;
    return st;
}

Upvotes: 4

Ben Stott
Ben Stott

Reputation: 2218

In C, you can't assign variables inside the struct.

You should initialise them in another function when each instance is created, however.

Upvotes: 1

Related Questions