问题描述
我最近发现一个有趣的行为g ++与MSVC ++ 2008相比。考虑这个小程序:
I recently found a interesting behaviour of g++ when compared with MSVC++ 2008. Consider this tiny program:
#include <cstdlib>
const int ARR_LENGTH = 512;
void doSomething( int iLen );
int main( int argc, char** argv )
{
doSomething( ARR_LENGTH );
return 0;
}
void doSomething( int iLen )
{
int iTest[iLen];
return;
}
它会编译吗?你有什么感想?根据我对C(或C ++)的知识,这不应该编译,因为我可以调用函数doSomething()与任何我想要的整数,因此iTest数组的大小不能在编译时确定。然而,当我尝试用g ++编译这个,它的工作正常。现在我可以理解这里可能发生了什么 - 编译器注意到,我调用这个函数只有一次传递编译时常量作为参数。一些严重的优化在这里...但是当我试图编译这个使用MSVC ++ 2008,我得到这个:
Will it compile? What do you think? According to my knowledge of C (or C++ for that matter), this should NOT compile, since i can call the function doSomething() with any integer i want, so the size of iTest array cannot be determined at compile time. However, when i try to compile this with g++, it works just fine. Now i can understand what probably happened here - the compiler noticed that i call this function only once passing a compile-time constant as a parameter. Some serious optimizations going on here... But when i try to compile this using MSVC++ 2008, i get this:
1>c:\prj\test\test.cpp(15) : error C2057: expected constant expression
1>c:\prj\test\test.cpp(15) : error C2466: cannot allocate an array of constant size 0
1>c:\prj\test\test.cpp(15) : error C2133: 'iTest' : unknown size
我的问题是如何符合语言的定义(C标准(C ++标准))?这是很好的g ++做这样的优化(在这种情况下很容易看到,但第一次,我遇到它,它是在一个大项目,它没有什么意义一见钟情)。
My question is: how does this comply with the definition of the language (the C standard (C++ standard))? Is it just fine for g++ to do such an optimization (which in this case is easy to see, but the first time i encountered it, it was in a large project and it did not make much sense at first sight).
推荐答案
C99(C标准的最新版本)允许动态大小的数组。
但是,Visual Studio(仅支持C89)不支持此功能。
C99 (the most recent version of the C standard) does allow dynamically sized arrays.However, the feature is not supported by Visual Studio (which only implements C89 support)
在C ++中,它不是,可能永远不会有效。
In C++ it is not, and probably will never be, valid.
这篇关于编译器与数组分配的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!