C99/C++ Compound Literals Compiling

在使用g++ 进行文件编译的过程中,有时候需要各种参数。
其中‘-pedantic’参数是用来让编译器在执行编译过程中选择ISO 标准。
如下文字摘自GCC 的manual:
The original ANSI C standard (X3.159-1989) was ratified in 1989 and published in 1990.
This standard was ratified as an ISO standard (ISO/IEC 9899:1990) later in 1990. There
were no technical differences between these publications, although the sections of the ANSI
standard were renumbered and became clauses in the ISO standard. This standard, in
both its forms, is commonly known as C89, or occasionally as C90, from the dates of
ratification. The ANSI standard, but not the ISO standard, also came with a Rationale
document. To select this standard in GCC, use one of the options ‘-ansi’, ‘-std=c89’ or
‘-std=iso9899:1990’; to obtain all the diagnostics required by the standard, you should
also specify ‘-pedantic’ (or ‘-pedantic-errors’ if you want them to be errors rather than
warnings).
就是说,要想让编译器按指定的ISO标准来编译文件的话,就要在命令中指定相应的参数
‘-std=iso9899:1990 -pedantic’。
如果想要让GCC对可能出现的语法不兼容问题提示error而非warning的话,就要用'-pedantic-errors'参数。
举个Compound Literals的例子:
compound literals是ISO C99标准支持的特征,
g++在使用参数‘-pedantic’以采用ISO C++标准编译时会认为这是语法错误。
(如果不使用这个参数,能编译通过)
  
第一行,表明了结构体foo的成员是一个整形变量和一个二维char数组。
第二行,给这个结构体foo赋实参:int: x+y
char: [ a, 0]
其中第二行的效果等同于:
 
同样可以这样构建一个数组: 如果compound literals的所有成员由constant表达式组成,以用其来初始化静态存储的对象,
那么compound-literal结构可以被强制转换成一个指向它第一个元素的指针,从而进行初始化。
char **foo = (char *[]) { "x", "y", "z" };
作为GNU的扩展,GCC允许表态存储对象被compound literals初始化.
(ISO C99标准不允许,因为initializer不是一个constant).
具体操作形如对象仅仅在当compound literal和对象本身类型一样时才能被花括号里面的列表初始化。
另外要注意的是Compound literals 的initializer列表必须为constant.
如果正在被初始化的对象有未知的数组类型,那么其大小(size)由compound literal的大小决定。
看下面几行代码:
        
其效果等同于:
      
再由实例看一下compound literal 在GCC 下的编译情况:
编译: g++ -o file file.cpp -g -pedantic-errors 
出错: error: ISO C++ forbids compound-literals
(如果去掉‘-pedantic-errors’,编译通过并可以执行)
这是编译器在告知用户如果要编译compound literal的话,应该像下面几行一样声明一个数组变量再进行初始化:
float fs[] = { 0.3, 0.5 };
a<2> obj(fs);

如此一来,编译即可通过。
原文地址:
========================
http://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Compound-Literals.html
====================
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/a8889e2e76a3dd6f
========================
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值