在C和C变长数组(VLA)++ [英] Variable length arrays (VLA) in C and C++

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

问题描述

可能重复:结果
  动态可变的文件范围数组

我有我需要澄清 VLA 以及其行为的概念。

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

AFIK,因为C99是可能的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;
}

上面的code声明了一个VLA在C99,因为常量修改不创建一个编译时间值。在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++.

正如其他人已经指出,VLA具有名副其实的可变长度(非 - 常量)在全球范围内是很难做出的感觉。将计算顺序是怎样的,例如如果长度EX pression会引用不同的编译单元的对象呢? 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.

这留下了关于该包含常量限定的对象,这是不允许的长度EX pressions C中的小的差距。这来自于一个事实,即这样的对象不是C标准被认为是整型常量前pressions。这可能会在未来的版本或许改变,但到现在为止的C委员会没有觉得有必要允许这样一件事:有,在扮演这一角色枚举常数C.他们唯一的限制是它们仅限于 INT 在C,这将是很好也有他们的为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天全站免登陆