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

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

问题描述

在初始化可变大小数组时,只要变量是 const,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};

那根本不会编译,但如果我不初始化 test[] 那么它会编译!这对我来说没有任何意义,因为据我所知,无论如何都需要根据数组的大小(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...

谢谢!

推荐答案

  • 数组的大小必须是一个常量整数表达式.
  • 整型文字是一个常量整型表达式.(int arr[5];)
  • 用常量表达式初始化的常量积分变量是常量表达式.(const int j = 4; const int i = j; int a[i];)

    用非常量表达式初始化的常量变量不是常量表达式

    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天全站免登陆