With struct
initialization via a compound literal, it will do the casting itself. For example:
struct movie {
char title[50];
int year;
};
typedef struct movie Item;
typedef struct node {
Item item;
struct node *next;
} Node;
typedef struct linkedlist {
Node *head;
size_t size;
} LinkedList;
LinkedList movies2 = {
.head=&(Node){{"Avatar", 2010}, NULL},
.size=1
};
However, if I separate the definition, I have to add in an explicit cast:
LinkedList movies2;
movies2 = (LinkedList) {
.head=&(Node){{"Avatar", 2010}, NULL},
.size=1
};
Code: https://godbolt.org/z/dG8nMh
And if I leave out the (cast_type)
in the second one I will get an error along the lines of error: expected expression before ‘{’ token
. Why is this so?
That is, why does the initialization not need the cast but the other definition does? My thought was the second version should be able to resolve itself without the explicit cast but obviously that is incorrect.
.head
assignment in that. – Jacobjacoba(LinkedList) {}
is not a cast. It is a syntax for compound literals, which you seem to be aware of. – Deathful