spooja__
spooja__

Reputation: 223

what happens if you create a variable length array and compile using g++

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;
}

Upvotes: 5

Views: 1116

Answers (1)

Zoso
Zoso

Reputation: 3465

GCC documents its support of VLAs here (emphasis mine)

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++.

CLANG documentation too follows suit but mentions clearly that the standard doesn't accept (emphasis mine)

GCC and C99 allow an array's size to be determined at run time. This extension is not permitted in standard C++. However, Clang supports such variable length arrays for compatibility with GNU C and C99 programs.

If you would prefer not to use this extension, you can always disable it with -Werror=vla to disallow compilation.

Upvotes: 7

Related Questions