Why is new int[n] valid when int array[n] is not?

前端 未结 9 2189
暗喜
暗喜 2020-12-31 02:00

For the following code:

foo(int n){
    int array[n];
}

I understand that this is invalid syntax and that it is invalid because the c++ sta

9条回答
  •  天命终不由人
    2020-12-31 02:33

    In the expression

    new int[n]
    

    int[n] is not the type. C++ treats "new with arrays" and "new with non-arrays" differently. The N3337 standard draft has this to say about new:

    When the allocated object is an array (that is, the noptr-new-declarator syntax is used or the new-type-id or type-id denotes an array type), the new-expression yields a pointer to the initial element (if any) of the array.

    The noptr-new-declarator refers to this special case (evaluate n and create the array of this size), see:

    noptr-new-declarator:

        [ expression ] attribute-specifier-seqopt

        noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt

    However you can't use this in the "usual" declarations like

    int array[n];
    

    or in the typedef

    typedef int variable_array[n];
    

    This is different with C99 VLAs, where both are allowed.

    Should I be using vectors instead?

    Yes, you should. You should use vectors all the time, unless you have a very strong reason to do otherwise (there was one time during the last 7 years when I used new - when I was implementing vector for a school assignment).

提交回复
热议问题