c++ - 使用 const int 作为数组大小

标签 c++ arrays constants

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

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

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

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

最佳答案

数组大小应该在编译时已知。

const int 如果值在编译时未知,则局部变量可能不起作用:

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

在这两种情况下,const int 表示该值不会改变,而不是在编译时已知。

关于c++ - 使用 const int 作为数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30476227/

相关文章:

c++ - 在 C++ 的 CC 编译器中使用 argv[]

c - C中静态和非静态数组的区别

javascript - 获取javascript数组中每个键的最大值

c++ - 构造函数中的 Const 参数导致 stackoverflow

c++ - 在 C++ 中动态创建 vector 并添加到 map

c++ - 如何将当前进程分配给新创建的作业对象?

c++ - 类模板偏特化

javascript - 删除数组中的单元格

c - 为长值显式声明 L 或 UL 的原因是什么

c++ - 将 const 容器引用作为参数传递时如何逃脱 const_iterator 陷阱