在 C99 中,如果 x
早先声明并且是 v2
类型,那么我可以这样写:
x = (v2) { 1, 2 };
v2
是:
typedef struct {
int x;
int y;
} v2;
我可以在 C90 中做类似的事情吗?
最佳答案
据我所知,复合字面量是在 C99 中引入的。但是,如果您使用的是 GCC,则此功能可作为扩展使用。引用 GCC docs :
ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++.
关于 GCC 的这个特性的另一个注释:
As a GNU extension, GCC allows initialization of objects with static storage duration by compound literals (which is not possible in ISO C99, because the initializer is not a constant). It is handled as if the object was initialized only with the bracket enclosed list if the types of the compound literal and the object match. The initializer list of the compound literal must be constant. If the object being initialized has array type of unknown size, the size is determined by compound literal size.
static struct foo x = (struct foo) {1, 'a', 'b'}; static int y[] = (int []) {1, 2, 3}; static int z[] = (int [3]) {1};
The above lines are equivalent to the following:
static struct foo x = {1, 'a', 'b'}; static int y[] = {1, 2, 3}; static int z[] = {1, 0, 0};
关于C90 复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10743804/