This is 变长数组 http://en.wikipedia.org/wiki/Variable-length_array or VLA这是一个C99特点但是gcc http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html and clang http://clang.llvm.org/compatibility.html#vla支持它作为扩展C++而视觉工作室does not http://msdn.microsoft.com/en-us/library/zb1574zs.aspx. So Visual Studio
在这种情况下遵守标准并且在技术上是正确的。并不是说扩展不好,Linux 内核依赖于许多 gcc 扩展 http://www.ibm.com/developerworks/library/l-gcc-hacks/,因此它们在某些情况下很有用。
如果您添加-pedantic
标记两者gcc
and clang
例如,会警告您这一点gcc
says (现场观看 http://coliru.stacked-crooked.com/a/67bafb84ad611631):
warning: ISO C++ forbids variable length array 'arr' [-Wvla]
int arr[size];
^
使用-pedantic-errors
标志将使这是一个错误。您可以在这些文档中阅读有关扩展的更多信息GCC 支持的语言标准 http://gcc.gnu.org/onlinedocs/gcc/Standards.html#Standards and clans 语言兼容性部分 http://clang.llvm.org/compatibility.html.
Update
The C++ 标准草案 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf涵盖什么是积分常量表达式在部分5.19
常量表达式段落3并说:
整型常量表达式是整型或无作用域枚举类型的表达式,隐式转换为纯右值,其中转换后的表达式是核心常量表达式。 [...]
从阅读本文中,所有可能性并不是直观明显的,但是Boost 整型常量表达式的编码指南 http://www.boost.org/development/int_const_guidelines.html这方面做得很好。
在这种情况下,因为您正在初始化size
with a literal using const足以使其成为积分常量表达式 (see [expr.const]p2.9.1 https://timsong-cpp.github.io/cppwp/n3337/expr.const#2.9.1)并使代码恢复标准C++:
const int size = 10;
using 常量表达式也会起作用:
constexpr int size = 10;
阅读可能会有所帮助之间的区别constexpr and const https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const.
作为参考,等效部分8.3.4
段落1 in the C99标准草案 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf将是部分6.7.5.2
数组声明符段落4其中说(强调我的):
If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope;124) such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.