-2

Any idea why this isn't working in C++? I feel like it's really simple, but I can't figure it out:

int main() {
  int arraySize = 5;
  char testArray[arraySize] = {'a', 'b', 'b', 'c', 'd'};
}

It works fine when I hard code 5 as the array size, but it doesn't like it when I use a variable name instead. Ultimately I'm trying to figure out how to write a function that deletes duplicate characters from the array, but I can't even get the array initialized.

1 Answers1

2

By default compilers are expecting mix of C++ and C code. So VLA is enabled as an extension. It is possible to enfore pure C++ then this code will fail to compile.

Note that msvc supports old C standard where VLA was not available yet, so in many multi-platform projects compilers are configured not to use VLA.

Now this warning:

variable-sized object may not be initialized

Basically says, you have requested VLA and you are initializing it with 5 elements. It may happen that arraySize variable can be changed during runtime to value less then 5 and this can corrupt your initialization code. That is why this warning is reported. Some initialization may be uncompleted.

Now your question was closed as duplicate indicating that C++ standard do not support VLA. I reopened it since question was about warning what is not covered by duplicate.

Marek R
  • 32,568
  • 6
  • 55
  • 140