是否始终允许C ++使用变量作为数组大小? [英] Has C++ Always Allowed Using A Variable for Array Size?

查看:259
本文介绍了是否始终允许C ++使用变量作为数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我回想起过去无法执行以下操作:

For some reason, in the past, I recall not being able to do something like:

int arraySize;
cin >> arraySize;

int array[arraySize];

但是最近,我再次尝试了此操作,并且没有引起任何问题.在这会在我的编译器(macOS Sierra,Xcode 8.1)中引发错误之前,我本可以发誓.语言是否进行了更新以允许这样做? -我可能会完全记错,这以前不是问题,但是我不确定.我认为数组大小必须在编译期间定义,并且用户无法选择它(这是实现动态数组的位置).

But recently, I tried this again and its not causing any issues. I could've sworn before this was something that threw an error in my compiler (macOS Sierra, Xcode 8.1). Was anything in the language updated to allow this? - I could be entirely remembering incorrectly and this wasn't an issue before, but I'm not sure. I thought array sizes had to be defined during compilation and the user couldn't pick that (which is where you would implement a dynamic array).

推荐答案

尽管某些编译器可以具有自己的语言扩展,从而允许在C ++程序中使用VLA,但C ++标准不支持可变长度数组.

The C++ Standard does not support variable length arrays though some compilers can have their own language extensions that allow to use VLAs in a C++ program.

因此,此代码段

int arraySize;
cin >> arraySize;

int array[arraySize];

不符合C ++.

使用标准C ++类std::vector.

对于C而言,根据C标准的实现可能有条件地支持VLA.

As for C then according to the C Standard implementations may conditionally support VLAs.

您可以检查实现是否支持VLA. 来自C标准(6.10.8.3条件功能宏)

You can check whether an implementation supports VLAs. From the C Standard (6.10.8.3 Conditional feature macros)

1以下宏名称由 实施:

1 The following macro names are conditionally defined by the implementation:

__STDC_NO_VLA__

整数常量1,旨在指示执行 不支持可变长度数组或可变修改类型.

The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified types.

这篇关于是否始终允许C ++使用变量作为数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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