Pradyumn
Pradyumn

Reputation: 430

C++ Array Definition with Lower and Upper Bound?

My daughter's 12th standard C++ textbook says that

the notation of an array can (also) be given as follows: Array name [lower bound L, upper bound U]

This was a surprise for me. I know Pascal has this notation, but C++? Had never seen this earlier. I wrote a quick program in her prescribed compiler (the ancient Turbo C++ 4.5), and that does not support it. Did not find this syntax in Stanley Lippman's book either. Internet search did not throw up this. Or maybe I didn't search correctly?

So, is it a valid declaration?

Upvotes: 4

Views: 1269

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158529

This is not valid, from the draft C++ standard section 8.3.4 Arrays the declaration must be of this form:

D1 [ constant-expressionopt] attribute-specifier-seqopt

and we can from section 5.19 Constant expressions the grammar for constant expression is:

constant-expression:
   conditional-expression

This grammar does not allow us to get to the comma operator either to do something like this:

int a[ 1, 2 ] ;
        ^

as others have implied since there is no path to comma operator from conditional-expression. Although if you add parenthesis we can get to the comma operator since conditional-expression allows us to get to primary-expression which gets us () so the following would be valid:

int a[ (1, 2) ] ;
       ^   ^

Note, in C++03 you were explicitly forbidden from using the comma operator in a constant expression.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234765

No it's not true, unless someone has overloaded the comma operator and possibly [] as well which is very unlikely. (Boost Spirit does both but for very different reasons).

Without any overloading at all, Array[x, y] is syntatically invalid since the size must be a constant-expression and these cannot contain the comma operator; as to do so would make it an assignment-expression.

Burn the book and put Stroustrup in her Christmas stocking!

Upvotes: 3

Related Questions