?
This document uses PHP Chinese website manual Release
構造一個指定類型的未命名對象,當僅需要一次數組,結構或聯合類型的變量時使用。
( type ) { initializer-list } | (since C99) |
---|
其中
type | - | a type name specifying any complete object type or an array of unknown size, but not a VLA |
---|---|---|
initializer-list | - | list of initializers suitable for initialization of an object of type |
復合文字表達式構造由 type 指定的類型的未命名對象,并按 initializer-list 的指定進行初始化。
復合文字的類型是 type(除非 type 是一個未知大小的數組;其大小是從初始化程序列表中推導出來的,與數組初始化中一樣)。
復合文字的值類別是左值(可以取其地址)。
如果復合文字出現在塊范圍(在這種情況下對象的生存期在封閉塊的末尾結束),則復合文字評估的未命名對象具有靜態(tài)存儲持續(xù)時間,前提是復合文字出現在文件范圍和自動存儲持續(xù)時間。
常量限定字符或寬字符數組類型的復合文字可能與字符串文字共享存儲空間。
(const char []){"abc"} == "abc" // might be 1 or 0, implementation-defined
每個復合文字在其范圍內僅創(chuàng)建一個對象:
int f (void){ struct s {int i;} *p = 0, *q; int j = 0;again: q = p, p = &((struct s){ j++ }); if (j < 2) goto again; // note; if a loop were used, it would end scope here, // which would terminate the lifetime of the compound literal // leaving p as a dangling pointer return p == q && q->i == 1; // always returns 1}
因為復合文字是未命名的,所以復合文字不能自我引用(一個已命名的結構可以包含一個指向自身的指針)。
盡管復合文字的語法類似于強制轉換,但重要的區(qū)別是,強制轉換是非左值表達式,而復合文字是左值。
int *p = (int[]){2, 4}; // creates an unnamed static array of type int[2] // initializes the array to the values {2, 4} // creates pointer p to point at the first element of the arrayconst float *pc = (const float []){1e0, 1e1, 1e2}; // read-only compound literal int main(void){ int n = 2, *p = &n; p = (int [2]){*p}; // creates an unnamed automatic array of type int[2] // initializes the first element to the value formerly held in *p // initializes the second element to zero // stores the address of the first element in p struct point {double x,y;}; void drawline1(struct point from, struct point to); void drawline2(struct point *from, struct point *to); drawline1((struct point){.x=1, .y=1}, // creates two structs with block scope (struct point){.x=3, .y=4}); // and calls drawline1, passing them by value drawline2(&(struct point){.x=1, .y=1}, // creates two structs with block scope &(struct point){.x=3, .y=4}); // and calls drawline2, passing their addresses}
C11 standard (ISO/IEC 9899:2011):
6.5.2.5 Compound literals (p: 85-87)
C99 standard (ISO/IEC 9899:1999):
6.5.2.5 Compound literals (p: 75-77)