使用const int作为数组大小 [英] Using const int as array size

查看:267
本文介绍了使用const int作为数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以使用本地声明的const int作为数组声明的大小,但不允许对作为参数传递的const int做相同的事情?

Why am I able to use a locally declared const int as the size of an array declaration but am not allowed to do the same with a const int passed as an argument?

例如,在下面的代码中,为什么我仅在第2行出现编译器错误?

For example, in the below code why do I get compiler errors only on line 2?

void f1(const int dim){
  int nums[dim];  // line 2: errors
}

void f2(){
  const int dim = 5;
  int nums[dim];  // ok
}

推荐答案

在编译时应该知道数组大小.

Array size should be known at compile time.

const int可能也不起作用:

void f2(){
  const int dim = bar();
  int nums[dim];  // error
}

在这两种情况下,const int都表明该值没有改变,而不是在编译时就知道了.

In Both case, const int tells that the value doesn't change, not that is it known at compile time.

这篇关于使用const int作为数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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