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?

3
  • Possible duplicate of Enabling VLAs (variable length arrays) in MS Visual C++? Commented Sep 15, 2019 at 16:19
  • It's one of the more inscrutable bits of the standard, but C11 §6.7.6.2 Array Declarators ¶4 defines variable length arrays. Just for once, this isn't a GCC extension. Commented Sep 15, 2019 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. Commented Sep 15, 2019 at 16:42

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You might add a note that VC only supports c90.
@JL2210 : ... plus those parts of C11 that are also valid C++ (but not VLAs because they are not).
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.