Are variable length arrays an extension in Clang too?

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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; } 

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!