2

In the marked line I get an error Error - expected expression

#include <stdlib.h>

struct list_head {
    struct list_head *next, *prev;
};

struct program_struct {
    const char *name;
    struct list_head node;
};
typedef struct program_struct program_t;

struct task_t {
    program_t blocked_list;
};

int main() {

    struct task_t *p = malloc(sizeof(*p));
    p->blocked_list.name = NULL;
    p->blocked_list.node = {&(p->blocked_list.node), &(p->blocked_list.node)}; //error

    return 0;
}

I know I can replace this line with

p->blocked_list.node.next = &(p->blocked_list.node);
p->blocked_list.node.prev = &(p->blocked_list.node);

But can I make it work using {} like I tried in the first piece of code?

1
  • 1
    Even though you can use a compound literal for this, there is no reason to do so. Instead use the most readable form, which is two rows: p->blocked_list.node.next = &p->blocked_list.node; p->blocked_list.node.prev = &p->blocked_list.node; This is the clearest form and therefore the one preferred. Commented Oct 14, 2016 at 8:33

1 Answer 1

2

Initialization is allowed only when you define a variable. So, you can't use initializers in assignment. You can instead use C99's compound literals:

p->blocked_list.node = (struct list_head) {&(p->blocked_list.node), &(p->blocked_list.node)}; //error
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that the compound literal defined by doing (struct list_head) {..} lives on until the current scope is left. To have it be deallocated immediately after the assignment just wrap the whole assignment statement into a new scope by enclosing it into braces {...}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.