C90 复合文字

标签 c standards c99 ansi c89

在 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/

相关文章:

c - 在堆栈上分配大小的字符串缓冲区的好方法是什么?

c# - 有没有一种方法可以跨不同语言标准化 Windows 事件日志查询?

c - 数组在循环中如何工作?

c - extern 关键字对 C 函数的影响

ios - 处理时区的移动行业标准是什么?

c - OpenCL 内核中通过指针访问变量

c - 类函数宏的扩展创建一个单独的标记

选择最合适的整数大小/范围用于变量

c - 预处理器包括路径、宏等条目不可用

c - 查找大小未知的循环链表的最后一个节点,最后一个节点指向除链表第一个节点以外的任何其他节点