为什么会出现与非恒定值数组定义中没有编译错误? [英] Why there is no compile error for the array definition with non-constant value?
问题描述
我想我应该得到下面的字符数组定义编译错误在 ALLDATA
I thought I should get compile error for the following char array definition of the allData:
void MyClass::aMethod(const char* data, int size)
{
int headerSize = 50;
MyHeader header;
//size is not constant and unknown at compile time
char allData[size + headerSize]; //<<<<<==== should not allowed!! but not error??
memcpy(allData, &header, headerSize);
memcpy(allData + headerSize, data, size);
....
}
为什么呢?它会给出一个运行时错误?
Why? It will give a run-time error?
推荐答案
GCC 和铛可能还有其他人虽然不是的 VISUAL C ++ ,支持的变长数组的,即使它是一个的 C99 的功能不是C ++的功能。
Both gcc and clang and possibly others although not visual C++, supports variable length arrays an extension even though it is a C99 feature not a C++ feature.
在两个 GCC
和铛
如果您使用 -pedantic $ C编译$ C>他们会提醒你,你正在使用的扩展,例如
GCC
将产生类似的警告是:
In both gcc
and clang
if you compile with -pedantic
they will warn you that you are using extensions, for example gcc
would produce a similar warning to this:
warning: ISO C++ forbids variable length array ‘allData’ [-Wvla]
您可以使用 -pedantic-错误
打开警告变成了错误。
据我了解的 C ++ 14 的可支持的变长数组的。 C99的标准草案 6.7.5.2
的数组声明的说道:
As far as I understand C++14 may support variable length arrays. The C99 draft standard section 6.7.5.2
Array declarators says:
[...]如果大小是整型常量前pression和元素类型有一个已知常数的大小,数组类型不是变长数组类型; ,否则,数组类型是一个可变长度的数组类型。
[...] 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.
而C ++标准草案要求在第一个常数时,C ++草案标准的 8.3.4
的阵列的说道:
while the C++ draft standard requires a constant, the draft C++ standard in section 8.3.4
Arrays says:
在声明T d设定其中D具有形式
In a declaration T D where D has the form
D1 [常量-EX pressionopt]属性说明符seqopt
D1 [ constant-expressionopt] attribute-specifier-seqopt
[..]如果常量-EX pression(5.19)是present,它应是一个类型为std转换后的恒前pression ::为size_t,其值应大于零。 [...]
[..] If the constant-expression (5.19) is present, it shall be a converted constant expression of type std::size_t and its value shall be greater than zero. [...]
这篇关于为什么会出现与非恒定值数组定义中没有编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!