c++数组长度必须是常量表达式
迷茫
迷茫 2017-04-17 14:41:34
0
5
696

我看c++ primer 第五版中文版时 看到了书上说数组的长度必须是常量表达式(书上的原话是指的维度,但感觉是翻译的问题,指的确实是长度),然后我试着用变量来写,能通过编译,这里是什么情况,是编译器没有检查,还是语法上本来就合法? 而且我在上面写了一个函数,返回值是int,没有标注constexpr,也可以作为数组的长度,同求解释。!

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(5)
Ty80

Objection @Agree and accept (Escape
You can use this test

int txt_size() {
  int a, b;
  scanf("%d%d", &a, &b);
  return a -b;
}

Visual inspection is that it has been expanded

PHPzhong

In VS2012, except int ib[4*7-14], which can be compiled, everything else fails. So the question is, is it really good for CB to extend language features like this?

左手右手慢动作

Because the value of the variable you wrote is determined,
the compiler has already obtained the exact value when allocating memory to the array.

左手右手慢动作

C++ array length cannot be changed, which is why a very large array storage queue is opened.

int q[10000001];  //C++的超大数组

It’s like there is a variable a, array h,

int a=2;
int h[a];   //此时等价于int h[2];
a=5;     //不管怎么变化,

h[4] does not exist at this time, you can try it.

迷茫

The possible reason is that your compiler also supports the C99 VLA, which is illegal in the sense of the C++ standard. You can try adding flags like -Wall -pedantic and compile again, you should get an error

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!