C90复合字面量

3
在C99中,如果先前声明了变量x并且类型为v2,那么我可以这样写:
x = (v2) { 1, 2 };

其中v2是:

typedef struct {
    int x;
    int y;
} v2;

我能在C90中做类似的事情吗?

3个回答

2
据我所知,复合字面量是在C99中引入的。然而,如果您使用的是GCC编译器,则该功能作为扩展可用。引用GCC文档
ISO C99支持复合字面量。复合字面量看起来像包含初始化程序的强制转换。它的值是指定转换中类型的对象,包含初始化程序中指定的元素;它是一个左值。作为一种扩展,GCC在C90模式和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};

2

如果不使用编译器扩展,在C90中最接近的方法是:

{
    v2 temp = { 1, 2 };
    x = temp;
}

你可以将其压缩为一行或者用宏替换它(当然,由于C语言没有卫生宏,所以你需要小心使用声明变量的宏)。


1
不,这是C99的特性。然而,一些编译器在C89模式下作为扩展允许它,例如gcc。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接