regomodo
regomodo

Reputation: 754

constexpr versus anonymous namespace

What is the difference between the following 2 patterns in creating const values?

constexpr int some_val = 0;

vs

namespace {
   const int some_val = 0;
}

I'm used to the 2nd method but is the 1st equivalent?

Upvotes: 0

Views: 2330

Answers (1)

Jarod42
Jarod42

Reputation: 218098

unnamed namespace acts as static: linkage of the variable.

namespace {
   const int some_val = 0;
}

is equivalent to:

static const int some_val = 0;

constexpr doesn't change that: Demo

Now we can compare const vs constexpr:

  • constexpr variable are immutable values known at compile time (and so can be used in constant expression)
  • const variable are immutable values which might be initialized at runtime.

so you might have

int get_int() {
    int res = 0; 
    std::cin >> res;
    return res;
}

const int value = get_int();

but not

constexpr int value = get_int(); // Invalid, `get_int` is not and cannot be constexpr

Finally some const values are considered as constexpr as it would be for:

const int some_val = 0; // equivalent to constexpr int some_val = 0;

Upvotes: 2

Related Questions