Enum type value as array length in C ++

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

const int MAX_Length=100; 

or

 #define MAX_LENGTH 100 

to determine the length of the array before compilation. But when I read the C ++ primer book from lippman, chapter 3.5.1 in the fifth release says: the length of the array must be a constant expression. Then the problem arises:

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

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

 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 the length of the array. is not it?

I am confused, could you help me? Thanks.

+6
source share
1 answer

In both enumerations, C ++ 11 and C ++ 03 (unscoped enums in C ++ 11) are integer constant expressions and therefore the boundaries of the array are used. We can see this for C ++ 11 by going to the draft C ++ 11 project , which reads:

An integral constant expression is an expression of an integral or non-enumerated type of enumeration implicitly converted to prvalue, where the converted expression is an expression of a constant constant. [Note: such expressions can be used as array boundaries (8.3.4, 5.3.4), since the bit field is of length (9.6), as initializers of the enumerator, if the base 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 closer than we can get the same section paragraph 1 which says:

[...] An integral constant expression can include only literals arithmetic types (2.13, 3.9.1), counters, non-volatile constants, variables or static data elements of integral or enumerated types, it is initialized with constant expressions (8.5), a template of a non-type type parameters of integral or enumerated types and the size of the expression [...]

In the registry, this code compiles fine for VC ++, so this is no longer a problem in current versions, it must be a bug in 2008, which was eventually fixed. It was also tested on the webcompiler , which was last updated on December 3, 2015, so this works in one of the latest releases.

An alternative could be to use const int, for example:

 const int len = LEN2 ; 

this will depend on whether Visual Studio 2008 considers counters to be integer constant expressions or just in the context of array boundaries, we hope that it will be only later.

C ++ 98

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

+6
source

Source: https://habr.com/ru/post/974064/


All Articles