Following code compiles fine since g++ allows it , but will it cause undefined behavior ? Or my code will work fine ? what does it mean that c++ standard disallows variable length array if no error is generated on using it ?
#include <iostream>
using namespace std;
int main()
{
int x;
cin >> x;
char abc[x];
cout << sizeof(abc) << "\n";
return 0;
}
sizeofoperator. The C++ Standard is open to extensions, and GCC's VLA support is such an extension. The behaviour is well defined, though I'll admit to not being a fan of the behaviour and recommend not using VLA. They are an extremely easy way to insert bugs into a program, particularly when you allow a user to specify the size.int arr[x] = {0};Initializes the first element to 0. Ifxis a compile-time constant, the rest of the array is also zeroed. Ifxis not a compile-time constant, the rest of the array is left containing whatever garbage happened to be where the array now lives in storage. This is a nasty surprise to many.