这是合法的C / C ++? `为int * p =(INT []){1,2,3};` [英] Is this legal C/C++? `int* p = (int[]) {1,2,3} ;`

查看:113
本文介绍了这是合法的C / C ++? `为int * p =(INT []){1,2,3};`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这个答案的产生一些评论声称,下面的结构是不合法的C / C ++:

 无效F(INT *一);
F((INT []){1,2,3,4,0});

(见一个完整的程序此ideone链接)。但是我们没能解决问题。任何人都可以揭示出这个任何光线?什么不同的标准有什么意见?


解决方案

这是有效的C99,据我可以告诉 - 这是通过一个复合文字

C99标准有这个作为一个例子(§6.5.2.5/ 9):


  

例1文件的范围定义


 为int * p =(INT []){2,4};


  

初​​始化p来指向两个整数的阵列的第一个元素,所述第一具有值的两个和第二,四。在该化合物的前pressions字面都要求是恒定的。该不愿透露姓名的对象具有静态存储时间。


请注意,(INT [])的事情是不是投在这里。

这不是一个有效的C ++虽然构造,复合文字不是C ++标准(C ++ 11在内)的一部分。一些编译器允许它作为一个分机。 (GCC呢,通过 -Wall -pedantic 来获得诊断一下吧。IBM了xlC <一个href=\"http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=%2Fcom.ibm.vacpp7l.doc%2Flanguage%2Fref%2Fclrc02compound_literals.htm\">allows它作为一个扩展太。)

This answer of mine generated some comments claiming that the following construct is not legal C/C++:

void f (int* a) ;
f ((int[]){1,2,3,4,0}) ;

(see this ideone link for a full program). But we weren't able to resolve the issue. Can anybody shed any light on this? What do the various standards have to say?

解决方案

It's valid C99 as far as I can tell - that's passing a compound literal.

The C99 standard has this as an example (§6.5.2.5/9):

EXAMPLE 1 The file scope definition

int *p = (int []){2, 4};

initializes p to point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant. The unnamed object has static storage duration.

Note that the (int []) thing is not a cast here.

This is not a valid C++ construct though, compound literals are not part of the C++ standard (C++11 included). Some compilers allow it as an extension. (GCC does, pass -Wall -pedantic to get a diagnostics about it. IBM xlC allows it as an extension too.)

这篇关于这是合法的C / C ++? `为int * p =(INT []){1,2,3};`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆