开发者

Can't assign struct variable in header file

I have a header file including a stru开发者_开发问答cture 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?


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.


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

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


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜