【C】C99的Designated Initializers特性

官方文档:http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

 

 

C99标准引入了Designated Initializers特性使得数组、结构体和联合体的初始化更加灵活和方便。

 对于一个数组:

int a[10] = { [1] = 1, [8 ... 9] = 10 };

这样可以只初始化a[1], a[8], a[9]三个元素,其他元素的值为0,相当于:

int a[10] = {0, 1, 0, 0, 0, 0, 0, 0, 10, 10};

对于一个结构体:

struct point {

    int x, y;

};

struct point p = { .y = 1, .x = 10 };

这相当于:

struct point p = { 10, 1 };

struct的特性也可以用于union。

这里的 '[index]'和 '.fieldname'称为designator。

使用这个特性你就可以按照任意顺序初始化数组、结构体和联合体中的成员了。

甚至,这两个designator还可以联合使用,例如:

struct point p_array[10] = { [1].x = 1, [2].y = 1 };

 

示例代码:

 1 /*gcc main.c -std=c99  */
 2 #include <stdio.h>
 3 struct point
 4 {
 5     int x, y;
 6 };
 7 int main()
 8 {
 9     /* for array */
10     int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
11     int a[6] = {[1]=1, 2, 3, [5]=5}; /* <=> [1]=1, [2]=2, [3]=3, [5]=5 */
12     for(int i=0; i<101; i++)
13         printf("%d ", widths[i]);
14     printf ("\n");
15     for(int i=0; i<6; i++)
16         printf ("%d ",a[i]);
17 
18     /* for struct */
19     struct point p1 = {.x=10, .y=11};
20     struct point p2 = {10,11};
21     struct point p3 = {x:10, y:11};
22     printf ("\n%d,%d\n%d,%d\n%d,%d\n",p1.x,p1.y,p2.x,p2.y,p3.x,p3.y);
23 
24     return 0;
25 }
d:/study/Program/cpp/expp $ gcc -g -o main.exe main.c --std=c99
d:/study/Program/cpp/expp $ ./main.exe 
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 
0 1 2 3 0 5 
10,11
10,11
10,11

 

 

posted @ 2012-04-11 11:54  visayafan  阅读(636)  评论(0编辑  收藏  举报