Kevin Wang
Kevin Wang

Reputation: 127

enum type value as the length of a array in C++

As we all know, the array length in C++ must be determined. Then we can use:

const int MAX_Length=100;

or:

#define MAX_LENGTH 100

to determined the length of an array before compilation. But, when I read the book c++ primer by lippman, in chapter 3.5.1 in 5th Edition, it says: the length of an array must be an constant expression. Then the problem comes:

typedef enum Length{LEN1=100, LEN2, LEN3, LEN4}LEN; 
LEN MAX_Length=LEN2;  //101
int iArray[LEN2];     //attention

the code compiled successfully in mingw32-g++. But failed in VS2008, and the errors are:

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'iArray' : unknown size

And I think the enum value is constant, so it should be used as an array's length. right?

I am confused, could you help me? Thank you.

Upvotes: 7

Views: 5179

Answers (1)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158489

In both C++11 and C++03 enumerators(unscoped enums in C++11) are integer constant expressions and therefore usable an array bounds. We can see this for C++11 by going to the draft C++11 standard section 5.19 [expr.const] which says:

An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression. [ Note: Such expressions may be used as array bounds (8.3.4, 5.3.4), as bit-field lengths (9.6), as enumerator initializers if the underlying type is not fixed (7.2), as null pointer constants (4.10), and as alignments (7.6.2). —end note ]

and or C++03 we can see this from the draft C++03 standard or the closest we can get same section paragraph 1 which says:

[...]An integral constant-expression can involve only literals of arithmetic types (2.13, 3.9.1), enumerators, non-volatile const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions[...]

On rextester this code compiles fine for VC++, so this is no longer an issue in current versions this must have been a bug in 2008 that was eventually fixed. Also tested on webcompiler which was last updated December 3rd 2015 so this works on one of the latest releases as well.

One alternative may be to use a const int for example:

const int len = LEN2 ;

this will depends on whether Visual Studio 2008 considers enumerators to not be integer constant expressions or whether it is just in the context of array bounds, hopefully it is just the later.

C++98

As far as I can tell this also applies to C++98 as well, both gcc and clang allow this when using -std=c++98, there are no draft C++98 standards available to the public so I can confirm beyond that.

Upvotes: 7

Related Questions