c - int q = {1,2};特殊的初始化列表

标签 c

我遇到了下面的初始化,可以看出VS2012 显示一个错误,提示太多的初始化程序。在 GCC 中似乎 返回第一个元素作为值。

为什么 GCC 支持这种特殊的初始化?

#include <stdio.h>

int main()
{
    int q = {1,2};
    char c = {'s','t','\0'};  /* c is 's' */
    printf("%d\n",q); /* prints 1*/
}

最佳答案

C11:6.7.9 初始化(p11):

The initializer for a scalar shall be a single expression, optionally enclosed in braces.

因此,这是允许的

int q = {1};   

您可以将标量对象的初始值设定项括在大括号 ({}) 中。请注意,这里使用了动词 shall。标准说:

5.1.1.3 诊断(P1):

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined

所以,这取决于编译器如何处理

int q = {1,2}; 

使用标志 -pedantic -Wall -Wextra 在 GCC 4.8.1 上编译并发出警告

[Warning] excess elements in scalar initializer [enabled by default]   

现在的问题是:What happend with the remaining initializers? 这是一个bug .


注意:C11:6.5.17 (p3) 指出逗号运算符不能出现在逗号用于分隔列表中的项目的上下文中(例如函数的参数或初始值设定项列表)。

不要将{1,2} 中的,逗号运算符 混淆。作为Keith Thompson指出,初始化器中的表达式是一个赋值表达式,并且它不能在顶层包含逗号运算符。这意味着它可以在括号内的表达式中使用,也可以在此类上下文中的条件运算符的第二个表达式中使用。在函数调用中

f(a, (t=3, t+2), c)

该函数有三个参数,第二个参数的值为 5

关于c - int q = {1,2};特殊的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28412577/

相关文章:

c - 将一行字写入C中的二维数组

c - 操作系统架构: Kernel and Standard Library interoperability

c - 在 Linux 中无法通过 C 执行“ls”命令

c - C.++ 与 |= 中的操作顺序,哪个先出现?

c - 使指针指向地址以便反射(reflect)更改

c - 尝试从 getchar() 获取变量以在简单的计算程序中保持其值

c - 术语 "format specifier"是术语 "conversion specifier"的同义词吗?

c - 包含多个表和一个 malloc() 的数组

c - 如何让malloc始终返回相同的地址?

c - libxml2 - xmlTextReaderPreservePattern - centos5 - libxml2-2.9.1 - gcc