我遇到了下面的初始化,可以看出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/