3

It says at msdn page for c++ constant expressions that:

Nonintegral constants must be converted (either explicitly or implicitly) to integral types to be legal in a constant expression. Therefore, the following code is legal:

const double Size = 11.0;
char chArray[(int)Size];

At least on VC++ 10.0 the second line produces: "error C2057: expected constant expression". So is it legal on some other compiler or is the msdn page simply wrong?

zeroes00
  • 531
  • 3
  • 16
  • g++ compiles this without problems. – fredoverflow Dec 23 '10 at 12:36
  • This is legal in java : final double Size = 11.0; char chArray = (int) Size; –  Dec 23 '10 at 12:42
  • 1
    @Sar: But that's not an array. – fredoverflow Dec 23 '10 at 12:52
  • This is also legel : final double Size = 11.0; char[] chArray = new char[(int) Size]; –  Dec 23 '10 at 12:53
  • @FredOverflow: Presumably because g++ by default supports C99 features as extensions in C++, and variable length arrays are allowed. VC++ does not support C99. – Clifford Dec 23 '10 at 12:59
  • @Sarang: Why does what's legal in Java have **anything** to do with what's legal in C++? You used `final` in that snippet and that's certainly not legal in C++.... – Billy ONeal Dec 23 '10 at 14:19
  • @Billy : its only because java made up from c++ –  Dec 23 '10 at 20:37
  • @Sarang: Err.. not really. C++ was standardized well after Java was already being used. More importantly, while C++ inspired lots of Java's design, they are different languages. Java allows assignment of default values inside the class declaration, C++ does not. C++ has the concept of a separate class declaration and definition. Java does not. – Billy ONeal Dec 23 '10 at 21:12

2 Answers2

6

According to 5.19/1 :

An integral constant-expression can involve only literals (2.13), enumerators, 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. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types.

From my understanding the code is invalid, while the following is legal :

char chArray[(int)11.0];
icecrime
  • 74,451
  • 13
  • 99
  • 111
3

That's not legal according to Standard C++. See 5.19/2 for the rules in the spec.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212