2

I have these two supposed constants:

int const MATRIX_SIZE = 1000;

int const LONGEST_LR_LINK = (int)floor(MATRIX_SIZE/2);

I am attempting to declare an array:

int lrLinkArray [LONGEST_LR_LINK];

I get the error:

error: array bound is not an integer constant before ‘]’ token

It would not be that much trouble to manually plug in whatever half MATRIX_SIZE is for LONGEST_LR_LINK, but I am curious as to what a solution to this would be. Is it bad practice to do any kind of calculation for a const?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Gerald
  • 521
  • 1
  • 6
  • 16

3 Answers3

7

Integer division in C++ automatically rounds down. So if you have the definition

int const LONGEST_LR_LINK = MATRIX_SIZE/2;

then LONGEST_LR_LINK will indeed be a constant expression, and

int lrLinkArray [LONGEST_LR_LINK];

should be fine. Besides, floor(MATRIX_SIZE/2) doesn't do what you think it does, anyway; you'd have to write floor(MATRIX_SIZE/2.0) in order to force non-integer division.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thank you. I guess I had it in my head that integer division would return a float remainder. – Gerald Jul 03 '14 at 17:57
3
int const LONGEST_LR_LINK = MATRIX_SIZE/2;

Integer division already rounds down.

jwodder
  • 54,758
  • 12
  • 108
  • 124
Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
2

Integer division should do what you want, we can see this from the draft C++ standard, in section 5.6 Multiplicative operators it says:

[...]For integral operands the / operator yields the algebraic quotient with any fractional part discarded;81[...]

To understand why it does not you have to realized that even though you initialize MATRIX_SIZE with a literal which makes it a constant expression std::floor is not a constexpr function and therefore LONGEST_LR_LINK is also not a constant expression and can not be used for array bounds which require an integral constant expression.

Also, as far I understand old style C casts are also not allowed in constant expressions either.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740