通过struct
复合文字进行初始化,它将自己进行转换。例如:
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
};
但是,如果我分开定义,我必须添加一个显式转换:
LinkedList movies2;
movies2 = (LinkedList) {
.head=&(Node){{"Avatar", 2010}, NULL},
.size=1
};
代码:https ://godbolt.org/z/dG8nMh
如果我(cast_type)
在第二个中省略了,我会得到一个错误 error: expected expression before ‘{’ token
。为什么会这样?
也就是说,为什么初始化不需要强制转换但其他定义需要?我的想法是第二个版本应该能够在没有显式转换的情况下自行解决,但显然这是不正确的。