4

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?

8
  • 5
    Turn on -pedantic-errors. Commented Nov 4, 2013 at 19:57
  • 3
    @abelenky it is an error for a standards compliant C++ compiler. Commented Nov 4, 2013 at 20:02
  • 1
    @GabrielL., Well, -pedentic-errors won't get you anywhere until you change the spelling. Commented Nov 4, 2013 at 20:10
  • 1
    @juanchopanza: I think I was pretty clear about saying it is not an error if your compiler supports it. Not all compilers are strictly 100% C++ compliant. Commented Nov 4, 2013 at 20:16
  • 1
    A diagnostic message is required for illegal code. A conforming compiler can choose to compile anyway. Commented Nov 4, 2013 at 20:24

2 Answers 2

8

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.

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]

and you can use -pedantic-errors to turn the warning into an error.

As far as I understand C++14 may support variable length arrays. The C99 draft standard section 6.7.5.2 Array declarators says:

[...] 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.

while the C++ draft standard requires a constant, the draft C++ standard in section 8.3.4 Arrays says:

In a declaration T D where D has the form

D1 [ constant-expressionopt] attribute-specifier-seqopt

[..] 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. [...]

Sign up to request clarification or add additional context in comments.

Comments

2

Some C++ compilers have an option that allows to use C VLA in C++.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.