Why is there no compilation error to define an array with a variable value?

I thought I should get a compilation error for the following char allData strong> array definition :

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? Will this give a runtime error?

+4
source share
2 answers

Both gcc and clang, and possibly others, but not visual C ++ , support variable length extension arrays , even if it is a C99 function, not C ++.

gcc clang, -pedantic, , , gcc :

warning: ISO C++ forbids variable length array ‘allData’ [-Wvla]

-pedantic-errors, .

, ++ 14 . C99 6.7.5.2 :

[...] , , ; - .

++ , ++ 8.3.4 Arrays :

T D, D

D1 [constant-expressionopt] attribute-specifier-seqopt

[..] (5.19), std:: size_t, . [...]

+8

++ , C VLA ++.

+2

All Articles