search

Home  >  Q&A  >  body text

c++数组长度必须是常量表达式

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

迷茫迷茫2807 days ago720

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:43:34

    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

    reply
    0
  • PHPz

    PHPz2017-04-17 14:43:34

    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?

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:43:34

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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:43:34

    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.

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:43:34

    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

    reply
    0
  • Cancelreply