7

I understand that VLAs are not part of C++11 and I have seen this slip by GCC. It is part of the reason I switched to Clang. But now I am seeing it Clang too. I am using clang 3.2 (one behind the latest) and I am compiling with -pedantic and -std=c++11

I expect my test to NOT compile yet it compiles and runs.

int myArray[ func_returning_random_int_definitely_not_constexpr( ) ];

Is this a compiler bug or an I missing something?

In response to the comment here is the random_int_function()

#include <random>
int random_int_function(int i) 
{
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(1,100);

    int random_int = distribution(generator);  

    return i + random_int;
}
ks1322
  • 33,961
  • 14
  • 109
  • 164
Arbalest
  • 1,095
  • 11
  • 23

3 Answers3

6

Yes, variable length arrays are supported in clang 3.2/3.3 contrary to the C++11 Standard (§ 8.3.4/1).

So as you say, a program such as:

#include <random>

int random_int_function(int i) 
{
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(1,100);

    int random_int = distribution(generator);  

    return i + random_int;
}

int main() {
    int myArray[ random_int_function( 0 ) ];
    (void)myArray;
    return 0;
}

compiles and runs. However, with the options -pedantic; -std=c++11 that you say you passed, clang 3.2/3,3 diagnoses:

warning: variable length arrays are a C99 feature [-Wvla]

The behaviour matches that of gcc (4.7.2/4.8.1), which warns more emphatically:

warning: ISO C++ forbids variable length array ‘myArray’ [-Wvla]

To make the diagnostic be an error, for either compiler, pass -Werror=vla.

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
  • 4
    `-pedantic-errors` may be more useful for making it an error: it makes everything an error that's triggered by `-pedantic`, not just VLAs. –  Jul 15 '13 at 10:07
  • Thanks Mike and hvd! I had been assuming that "-pedantic" triggered errors, not just warnings. Both "-Werror" and "-pedantic-errors" do what I want and are great to know about. – Arbalest Jul 15 '13 at 15:13
1

Use these options:

  1. -Wvla to warning vla uses
  2. -Werror=vla to consider vla an error.

This works in both the clang and gcc compilers.

Mansoor
  • 2,357
  • 1
  • 17
  • 27
0

Simply plugging the snippets you posted into IDEone, without putting the array declaration into a function, I get

prog.cpp:12:39: error: array bound is not an integer constant before ‘]’ token

Adding a main() function around it results in success, as you observed.

Since C++11 doesn't allow for array declarations that are legal in main but not namespace scope, and that is a property of VLAs, it is reasonable to conclude that is what you are seeing.

Update: courtesy Coliru.org, the message from Clang is

main.cpp:12:9: error: variable length array declaration not allowed at file scope

So that's fairly definite.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421