这是合法的 C/C++ 吗? `int* p = (int[]) {1,2,3} ;`
我的这个答案生成了一些评论,声称以下构造不是合法的 C/C++:(
void f (int* a) ;
f ((int[]){1,2,3,4,0}) ;
请参阅 此 ideone 链接 以获得完整程序)。但我们没能解决这个问题。有人能解释一下吗?各种标准都有什么规定?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,它是有效的 C99 - 这是传递一个复合文字。
C99 标准以此为例(§6.5.2.5/9):
请注意,这里的
(int [])
并不是强制转换。但这不是有效的 C++ 构造,复合文字不是 C++ 标准的一部分(包括 C++11)。一些编译器允许它作为扩展。 (GCC 确实如此,通过
-Wall -pedantic
来获取有关它的诊断信息。IBM xlC 允许将其作为扩展也是。)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):
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.)作为参数传递给函数的表达式是复合文字的示例。这些在 C99 中是合法的,但在 C++98 中不合法。
例如,请参见 N897“C99 标准的基本原理草案。” 另请参阅 GCC 文档的此部分。
The expression passed as argument to the function is an example of a compound literal. These are legal in C99, but not in C++98.
See for example section 6.4.4 "Constants" and 6.8 "Statements and blocks" in N897 "A draft rationale for the C99 standard." See also this section of GCC documentation.
嗯,我认为根据 C++11 它是有效的。第 5.2 节:
编辑:
经过更多阅读后,我得出结论,它实际上是无效,因为你不能使用这样的后缀表达式。应该有一些主要的表达。
Well, I think it is valid according to C++11. Section 5.2:
EDIT:
After some more reading I came to conclusion it's actually invalid, because you cannot use postfix expression like that. There should be some primary expression.