c++数组是否可以在运行时确定长度并且进行初始化
今天在家中阅读c++ primer复习c++语法的知识,看到了2.4.4 constexpr和常量表达式这一章节
它说常量表达式(const expression)是指值不会改变并且在编译过程就能得到计算结果的表达式.。被const修饰的对象也不一定是常量表达式。
我想了想需要用到常量表达式应该有数组了。但是在c++中被const修饰的对象能为数组定义长度(在c中不能),于是我编写了一段程序测试const对象为非常量表达式并且在运行时才能确定值的时候能否成功定义数组。
#include <iostream>
#include <string>
using namespace std;
int get_size(int vsz);
int main()
{
const int size=get_size(2);
int array[size]={1,2,3,4,5,6,7,8,9};
cout<<endl;
for(auto p:array)
{
cout<<p<<endl;
}
return 0;
}
int get_size(int vsz)
{
int i;
cin>>i;
return vsz*i;
}
get_size为传入的值提供程序运行后用户输入的值的倍数。该值在程序运行后才能确定。
array数组大小应该在编译时就要确定大小。但是该程序在g++ (Debian 6.3.0-18+deb9u1) 6.3.0编译器中编译通过,并且除了输入1外也正确。
./a.out
1
段错误
./a.out
2
1
2
3
4
./a.out
6
1
2
3
4
5
6
7
8
9
0
0
0
数组实现了在运行时确定长度并且进行初始化。虽然1报错