C 和 C++ 中的可变长度数组 (VLA) [英] Variable length arrays (VLA) in C and C++

查看:42
本文介绍了C 和 C++ 中的可变长度数组 (VLA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
文件范围内的可变修改数组

我有一些关于 VLA 及其行为的概念,我需要澄清.

I have some concepts about the VLA and its behavior that I need to clarify.

从 C99 开始的 AFIK 可以将 VLA 声明为本地范围:

AFIK since C99 it's possible to declare VLA into local scopes:

int main(int argc, char **argv)
{
    // function 'main' scope
    int size = 100;
    int array[size];
    return 0;
}

但在全局范围内是禁止的:

But it is forbidden in global scopes:

const int global_size = 100;
int global_array[global_size]; // forbidden in C99, allowed in C++

int main(int argc, char **argv)
{
    int local_size = 100;
    int local_array[local_size];
    return 0;
}

上面的代码在 C99 中声明了一个 VLA,因为 const 修饰符不会创建编译时值.在 C++ 中,global_size 是一个编译时值,所以 global_array 不会成为 VLA.

The code above declares a VLA in C99 because the const modifier doesn't creates a compile-time value. In C++ global_size is a compile-time value so, global_array doesn't becomes a VLA.

我需要知道的是:我的推理是否正确?我所描述的行为是否正确?

What I need to know is: Is my reasoning correct? The behaviour that I've described is correct?

我还想知道:为什么不允许全局范围内的 VLA?在 C 和 C++ 中都被禁止吗?什么原因导致数组进入全局和局部范围的行为不同?

I also want to know: Why the VLA in global scope aren't allowed? are forbidden both in C and C++? What reason is there for the behavior of arrays into global and local scope were different?

推荐答案

是的,你的推理是正确的,这就是 C 和 C++ 如何看待这些不同形式的数组声明和定义.

Yes your reasoning is correct, that is how these different forms of array declarations and definitions are viewed by C and C++.

正如其他人已经说过的那样,在全局范围内具有真正可变长度(非const)的 VLA 很难理解.评估顺序是什么,例如,如果长度表达式将引用不同编译单元的对象?C++ 没有 VLA,但它具有文件范围内对象的动态初始化.如果你不得不依赖求值顺序,这已经让你头疼了.

As others already stated, VLA with a veritable variable length (non-const) in global scope is difficult to make sense. What would the evaluation order be, e.g if the the length expression would refer to an object of a different compilation unit? C++ doesn't have VLA, but it has dynamic initialization of objects at file scope. And already this gives you quite a head ache, if you have to rely on evaluation order.

这给 C 留下了一个关于包含 const 限定对象的长度表达式的小差距,这是不允许的.这是因为这样的对象不被 C 标准视为整数常量表达式".这可能会在未来的版本中改变,但到目前为止,C 委员会认为没有必要允许这样的事情:有 enum 常量在 C 中扮演这个角色.他们唯一的限制是它们仅限于 C 中的 int,如果也有它们 size_t,那就太好了.

This leaves the small gap for C concerning length expressions that contain a const qualified object, which isn't allowed. This comes from the fact that such objects are not considered "integer constant expressions" by the C standard. This could perhaps change in future versions, but up to now the C committee didn't find it necessary to allow for such a thing: there are enum constants that play that role in C. Their only limitation is that they are limited to int in C, it would be nice to also have them size_t.

这篇关于C 和 C++ 中的可变长度数组 (VLA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆