Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which compiler should I trust?

This is going to be some what of a newbie question but I was trying to work on a small exercise in the C Language (not C++) and I was running into some issues.

Say I wanted to use an array within a method whose size depended on one of the arguments:

void someFunc(int arSize)
{
    char charArray[arSize];
    // DO STUFF
    ...
}

When I try to compile this as a .c file within Visual Studio 2013 I get an error saying that a non-constant array size is not allowed. However the same code works within CodeBlocks under a GNU Compiler. Which should I trust? Is this normal for compilers to behave so differently? I always thought that if you're doing something that a compiler doesn't like you shouldn't be doing it in the first place because it's not a standard.

Any input is useful! I come from a Background in Python and I am trying to get more heavily involved in programming with Data-Structures and Algorithms.

My platform is Windows as you can probably tell. Please let me know if this question needs more information before it can be answered.

like image 399
Валера Горбунов Avatar asked Dec 07 '22 05:12

Валера Горбунов


2 Answers

Variable length arrays(VLA) are a C99 feature and Visual Studio until recently did not support C99 and I am not sure if it currently supports VLA in the lastest version. gcc on the other hand does support C99 although not fully. gcc supports VLA as an extension outside of C99 mode, even in C++.

From the draft C99 standard section 6.7.5.2 Array declarators paragraph 4:

[...] If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

like image 111
Shafik Yaghmour Avatar answered Dec 16 '22 22:12

Shafik Yaghmour


You should trust the compilers that you're using and that you want to support.

On that particular issue: non-constant array sizes are valid in C99, which isn't fully supported by either gcc or by MSVC (Microsoft's C/C++ compiler). gcc, however, has this feature from the standard implemented even outside of C99 mode, while MSVC hasn't.

like image 34
Renan Gemignani Avatar answered Dec 16 '22 22:12

Renan Gemignani