为什么我不能初始化一个变量大小的数组? [英] Why can't I initialize a variable-sized array?

查看:651
本文介绍了为什么我不能初始化一个变量大小的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC没有给出错误的时候,你只要变量是常数初始化变量大小的数组,但是当它不是,它不会编译。

GCC gives no error when you initialize a variable-sized array as long as the variable is const, but when it isn't, it won't compile.

什么是这背后的原因是什么?这有什么错这样做的:

What's the reason behind this? What's so wrong with doing:

int size = 7;
int test[size] = {3, 4, 5};

这不会编译所有,但如果我不初始化测试[],然后它编译!这没有任何意义,我,因为据我所知堆栈帧需要作出根据其大小(7整数)无论什么(这意味着我用的是整数文字真的不适合这个数组有什么意义,如果我没有记错的话),所以没有什么区别,如果我初始化与否?

That won't compile at all, but if I don't initialize test[] then it does compile! That doesn't make any sense to me, because as far as I know a stack frame needs to be made to fit this array according to its size(7 ints) no matter what(which means the integer literals I use don't really have any meaning, if I'm not mistaken), so what difference does it make if I initialize it or not?

只是我疯了C ++的设计问题,另一个...

Just another one of my crazy C++ design questions...

谢谢!

推荐答案


  • 数组的大小必须是一个整型常量前pression。

  • 一个不可分割的文字是一个整型常量前pression。 ( INT ARR [5];

  • 以恒定的前pression初始化常量积分变是一个不断前pression。 ( const int的J = 4; const int的我=焦耳; int类型的[I];

与非恒定的前pression初始化一个常变量不是一个常量前pression

A constant variable initialized with a non-constant expression is not a constant expression

 int x = 4;  // x isn't constant expression because it is not const
 const int y = x; //therefore y is not either
 int arr[y]; //error)


这篇关于为什么我不能初始化一个变量大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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