Skip to the content.

Designated Initializers (指定初始化)

1. struct

如果我們定義了以下一個結構體,有三種可行的初始化方法:

struct test_struct {
  int i;
  float f;
};

初始化方法1:(指定初始化第一種)

struct test_struct first_kind = {.i = 1, .f = 1.1};

初始化方法2: (指定初始化第二種。這是我們最常用的一種賦值方法之一,但是根據[gnu官方網站][https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html],這種方法已經被淘汰/過時了,但是仍然在支持。)

struct test_struct second_kind = {i : 1, f : 1.1};

初始化方法3:(這種方法的缺點是,賦值時必須struct中每個元素,一個不漏的全部賦值,不如前兩個靈活。)

struct test_struct third_kind = {1, 1.1};

2. 數組

對數組,也有三種可行的初始化方法:

初始化方法1:(順序初始化,a中的6個元素分別是:1,2,3,4,5,0。這種初始化方法缺少一點點靈活性。)

int a[6] = {1, 2, 3, 4, 5};

初始化方法2:(示例中初始化了b[2]=2,b[5]=5。b中6個元素分別是:0,0,2,0,0,5。這種初始化方法比較靈活。)

int b[6] = {[2] = 2, [5] = 5};

初始化方法3:(示例中初始化了c[2]=c[3]=c[4]=c[5]=4。c中6個元素分別是:0,0,4,4,4,4。這種初始化方法適合用在將一定範圍內的數據統一初始化某一值的情況。)

int c[6] = {[2 ... 5] = 4};