在数组声明中const int和int之间的区别? [英] Difference between const int and int in an array declaration?

查看:445
本文介绍了在数组声明中const int和int之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这种类型的声明

int nArraySize = 7;
char szName[nArraySize] = "Mollie";

返回此错误:

error: variable-sized object 'szName' may not be initialized

当我声明'arraySize'变量作为一个'const int'它工作吗?

but when I declare the 'arraySize' variable as a 'const int' it works ?

const int nArraySize = 7;
char szName[nArraySize] = "Mollie";


推荐答案

必须首先说的是,在C ++语言中,数组声明的大小部分需要是积分常数表达式(ICE)。用初始化器声明的 const int 对象可以在ICE中使用。不能在ICE中使用 int 对象。

It must be said first that in C++ language, the size part of array declaration is required to be an Integral Constant Expression (ICE). A const int object declared with an initializer can be used in an ICE. An int object cannot be used in an ICE. That's the formal part of it.

但是,根据错误消息,您的C ++编译器支持 C99风格的可变长度数组)在C ++中,作为非标准扩展。这意味着在你的编译器中,允许使用非常量表达式来指定数组声明中的大小。然而,即使支持VLA本身,这样的阵列仍然不能被初始化。这是C99中的VLA的规范所禁止的,这正是它们的规范是如何被C ++编译器继承的。

However, judging by the error message, your C++ compiler supports C99-style variable-length arrays (VLA) in C++, as a non-standard extension. That means that in your compiler you are allowed to use non-constant expressions to specify size in array declarations. Yet even if VLAs themselves are supported, such arrays still cannot be initialized. This is prohibited by the specification of VLAs in C99, and that is exactly how their specification is "inherited" by your C++ compiler.

换句话说,与其他

int nArraySize = 7;
char szName[nArraySize];

即使它是非法的C ++。它是触发错误的 =Mollie部分。

even though it is formally illegal C++. It is the = "Mollie" part that triggers the error.

这篇关于在数组声明中const int和int之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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