0

I'm creating static array of chars which size is defined runtime. And I'm not getting compilation errors.
How is this possible?
Here is my example:

void f(const string& val) {
    char valBuf[val.size() + 1]; strcpy(valBuf, val.c_str());
    cout << valBuf << endl;

  }

int main() {
    string str = "aaaa";
    f(str);

    return 0;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Heghine
  • 435
  • 3
  • 15
  • Some compilers have this extension. If you compile in strict C++ mode, it should produce an error. – juanchopanza Aug 13 '14 at 14:36
  • Variable length arrays are a c99 feature [but several compilers include it as an extension](http://stackoverflow.com/questions/21273829/does-int-size-10-yield-a-constant-expression), possibly a duplicate. – Shafik Yaghmour Aug 13 '14 at 14:37
  • Yes, this is normally only available in C99 and later. – Overv Aug 13 '14 at 14:37
  • If you don't need to change the string, you can use `const char *p = val.c_str();` – Neil Kirk Aug 13 '14 at 14:40
  • 1
    I've recently asked a couple of questions on VLAs: 1. http://stackoverflow.com/q/24981392/1382251. 2. http://stackoverflow.com/q/24989715/1382251. You might find their answers useful.. – barak manos Aug 13 '14 at 14:42
  • This is just a dummy example :) in my real code I'm changing array. – Heghine Aug 13 '14 at 14:42
  • @Heghine: "Static array"? Where? I don't see any static arrays in the code you posted. Array `valBuf` is automatic (local), not static. If you attempt to make it static, then even an "extended" compiler will certainly complain. Static arrays are always required to have constant (compile-time) size. – AnT stands with Russia Aug 13 '14 at 18:18

1 Answers1

4

VLAs (i.e. variable length arrays) are a feature of C99 which some C++ compilers (GCC, for example) support as an extension.

This is not allowed under standard C++.