Selman Genç
Selman Genç

Reputation: 101742

How to declare a constant expression correctly?

I'm reading The C++ Programming Language and trying to understand Constants. The book says this is valid:

const int dmv = 17; // dmv is a named constant
constexpr double max1 = 1.4∗square(dmv); // OK if square(17) is a constant expression

But when I do:

constexpr double square(double x)
{
    return x * x;
}

int main()
{ 
    const double x = 40.0;
    constexpr double result = 1.2 + square(x);
}

I got two errors:

  1. expression must have a constant value (in x, if I replace it with a value for ex. 12.4 like square(12.4) the error disappears)
  2. function call must have a constant value in a constant expression (in square method call.)

What is the reason of those errors ? What am I missing ?

Upvotes: 0

Views: 5666

Answers (1)

user743382
user743382

Reputation:

Prior to C++11, constexpr didn't exist, and compile-time arithmetic was only possible for integer types (more or less).

In that language, it made sense to make const int "variables" truly constant whenever possible, and not so for const double.

C++11 introduces constexpr, so that the special rule for const T variables is no longer necessary, but removing the rule would unnecessarily break existing code. C++11 also introduces compile-time floating-point arithmetic, but because const double variables were never treated as constant expressions before, and there is little benefit in changing that now, you need to explicitly say constexpr.

constexpr double square(double x)
{
  return x * x;
}

int main()
{ 
  constexpr double x = 40.0;
  constexpr double result = 1.2 + square(x);
}

Upvotes: 1

Related Questions