编译器与数组分配的不同行为

编程入门 行业动态 更新时间:2024-10-20 15:59:51
本文介绍了编译器与数组分配的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近发现一个有趣的行为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.

更多推荐

编译器与数组分配的不同行为

本文发布于:2023-11-15 23:27:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   数组   分配

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!