1

Under GCC 4.8.1

static int len = 10;
int main() {
    int a[len];
    return 0;
}

can compile success.

But compile will fail if changed like this:

static int len = 10;
int main() {
    static int a[len];
    return 0;
}

But in my Visual Studio, the former also can not compile success. How can I fix this problem? And is there a way to change latter one to make it compile success?

Joe Lu
  • 551
  • 2
  • 7
  • 14
  • If you want to use Visual Studio, the obvious fix is to replace the VLAs by pointers and explicitly malloc the memory. In C99 they are really a rather minor conviencence and are easy enough to live without. – John Coleman Apr 16 '16 at 10:50
  • @JohnColeman You're right, but I disagree with VLAs being "a minor convenience". In most implementations, they're segfaults waiting to happen, because they're essentially uncontrollable calls to `alloca()`. –  Apr 16 '16 at 11:16
  • @Rhymoid Is that why C11 took a step back from them? – John Coleman Apr 16 '16 at 11:18
  • @JohnColeman I don't know. The C11 rationale hasn't been published yet. Hurray, standards organisations. –  Apr 16 '16 at 11:33

2 Answers2

1

The MSVC compiler only supports C90, it does not support C99, and variable length arrays are a feature of C99.

See this; it's not possible even with MSVC++.

Community
  • 1
  • 1
RastaJedi
  • 641
  • 1
  • 6
  • 18
0

The MSVC on windows does not support VLAs yet, so you will need to make the array with dynamic memory allocation:

static int len = 10;
int main() {
    int *a = malloc(len * sizeof(int));
    if (a == NULL) exit(1);
    return 0;
}
fluter
  • 13,238
  • 8
  • 62
  • 100