指定初始化
C99中提供了一種新的初始化方式:指定初始化(designated initialization)。這種初始化方式是少數幾個C和C++不兼容的地方之一,學校裏也很少會教。但是這個語法糖實在是很有用,可以少打很多字。
結構體
struct S {
int x;
int y;
};
void foo() {
struct S obj1 = {.x = 1, .y = 2};
// obj1 = {1, 2}
struct S obj2 = {.y = 2};
// obj2 = {0, 2}
}
數組
void bar() {
int a[5] = {[2] = 2, [4] = 4};
// a = {0, 0, 2, 0, 4}
}
混用
struct S {
int x;
int y;
};
void uwu() {
struct S sa[3] = {[1].y = 2};
// sa = {{0, 0}, {0, 2}, {0, 0}}
}
用於在堆上初始化
struct S {
int x;
int y;
};
void foo() {
struct S *ptr = malloc(sizeof(struct S));
*ptr = (struct S){.y = 2};
// ptr->x == 0 && ptr->y == 2
}