1

This code:

int main() {
   int size;
   scanf("%d", &size);
   int array[size]; 
}

works fine with GCC, but VC expects a constant expression for the size of the array so does not compile it (which makes more sense to me). Any idea why it works with GCC?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
  • Possible duplicate of [Enabling VLAs (variable length arrays) in MS Visual C++?](https://stackoverflow.com/questions/5246900/enabling-vlas-variable-length-arrays-in-ms-visual-c) – walnut Sep 15 '19 at 16:19
  • It's one of the more inscrutable bits of the standard, but C11 [§6.7.6.2 Array Declarators ¶4](https://port70.net/~nsz/c/c11/n1570.html#6.7.6.2p4) defines variable length arrays. Just for once, this isn't a GCC extension. – Jonathan Leffler Sep 15 '19 at 16:28
  • Try adding `printf("%d",size);` just after the line `int size;`. I'm not sure, maybe it's because of the garbage value. – Maifee Ul Asad Sep 15 '19 at 16:42

2 Answers2

3

Yes, because gcc supports variable length arrays.

It was added as a part of C99 standard, however, in the later standards (C11 and C18), it's an optional feature.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Because variable-length arrays (VLAs) are neither valid in C90 nor C++11 MSVC does not support them:

From https://learn.microsoft.com/en-us/cpp/build/reference/za-ze-disable-language-extensions?view=vs-2019:(

The C compiler is an C89/C90 compiler that, by default, enables Microsoft extensions to the C language.

VLAs may be best avoided in any event because a C11 compiler need not implement them and they are potentially unsafe. Typically an implementation will allocate VLAs on the stack. In your code, it only takes a user to enter an arbitrarily large value to break your code in someone-deterministic manner - any use of VLAs should have some constraint test to ensure the length is reasonable and in the capability of the system to support.

Clifford
  • 88,407
  • 13
  • 85
  • 165