在C99中,如果先前声明了变量
x
并且类型为v2
,那么我可以这样写:x = (v2) { 1, 2 };
其中v2
是:
typedef struct {
int x;
int y;
} v2;
我能在C90中做类似的事情吗?
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中最接近的方法是:
{
v2 temp = { 1, 2 };
x = temp;
}
你可以将其压缩为一行或者用宏替换它(当然,由于C语言没有卫生宏,所以你需要小心使用声明变量的宏)。