0

In order to prepare an array, I wrote code below.

#include <iostream>

using namespace std;

int main(){
  const double a=0.1;
  const double b=0.01;
  const int num=a/b;

  double array[num];
  return 0;
}

Then, I got an error: expression must have a constant value.

I don't know how to avoid this error. I searched on the internet, but I couldn't find the solution.

my PC window

Gaku Akita
  • 29
  • 6
  • 1
    This is a bit surprising since I would think that `num` should qualify as a constant expression. And over in [GCC](https://godbolt.org/z/T98v4jsad) I don't get a warning even with `-Wpedantic` on to complain about variable-length arrays. Not sure the duplicate targets are correct here. – Nathan Pierson Aug 13 '22 at 05:22
  • It looks like the rules that allow `const int arraySize = 10; double array[arraySize];` to be valid [treat integral types differently than floating point types](https://en.cppreference.com/w/cpp/language/constant_expression#Usable_in_constant_expressions). So maybe GCC is actually wrong to accept this code. – Nathan Pierson Aug 13 '22 at 05:37
  • @NathanPierson Yes GCC is wrong to accept it without diagnostic. `double` and other non-integral variables must be marked `constexpr` to be usable in constant expressions. `const` is not sufficient. – user17732522 Aug 13 '22 at 07:44
  • It seems wrong to use `double` to begin with. It is non-trivial to guarantee that the result of floating-point arithmetic truncated to an integral value is actually what you expect it to be. For example the size of the array could easily be `9` instead of `10` in this case due to inexact arithmetic and/or value representations. So why are you using `double` anyway? If the values are intended to be compile-time constants use `constexpr` instead of `const`. If they are not intended to be compile-time constants, then the size of the array cannot be determined by them. Use `std::vector` instead. – user17732522 Aug 13 '22 at 07:48
  • The underlying issue is that some aspects of floating-point arithmetic can be set at runtime, so the compiler can't, in general, know at compile time what the exact result of `a/b` will be. Yes, in this simple program it's obvious, but in more complex code there's simply no way to know. That's why [`constexpr`](https://en.cppreference.com/w/cpp/language/constexpr) was invented: it tells the compiler to do the evaluation at compile time. – Pete Becker Aug 13 '22 at 12:42
  • Thank you for helping me. I'm a beginner and I couldn't understand all the comments because of lack of knowledge. When I just focus on the solution to the problem I encountered, with the help of the comments, I found out that by replacing ```const```with ```constexpr```, I can avoid this error. Also, if I use ```vector``` instead of ```array```, I can solve this without using ```constexpr``` – Gaku Akita Aug 14 '22 at 14:10

0 Answers0