TITLE: constants and variables in new array expressions (Newsgroups: comp.std.c++, 12 Jan 97) LILLEY: jlilley@empathy.com (John Lilley) >I have a question about new-expression in the grammar. Apparently, the >subscripted form of the new-type-id only accepts a constant expression >for the subscript (according to the may96 DWP). But several compilers >and lots of code I have seen uses non-constant expressions like: >void f() { > int length = 7; > char *p = new char[length]; >} >Popular books and standard libraries have examples of this usage. Is >this version of the draft wrong? Should non-constant expressions be >allowed? How else does one allocate a variable-sized array of char? CLAMAGE: stephen.clamage@eng.sun.com (Steve Clamage) I believe you are misreading the draft. The new-type-id looks like this: new_type_id: type_specifier_seq [ new_declarator ] new_declarator: ptr_operator [ new_declarator ] direct_new_declarator direct_new_declarator: '[' expression ']' direct_new_declarator '[' constant_expression ']' In other words, the new_declarator is an expression in brackets, or an expression in brackets followed by one or more constant_expressions. If a and b are variables, you can write new int[5] new int[a] new int[a][5] but not new int[a][b] As always, the second and subsequent dimensions of an array must be constant.