0

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?

regomodo
  • 644
  • 3
  • 9
  • 18
  • *Why* are you using the second method? In particular, what do you think is the effect of using an unnamed namespace here? I suspect that you’re not quite clear on its effect (= nonexistent). – Konrad Rudolph Mar 25 '19 at 11:45
  • 2
    Unnamed namespaces would compare to `static`, not `constexpr`. – Jarod42 Mar 25 '19 at 12:32
  • Why you have put the second alternative in the namespace? Is there any reason behind that? The title of your Q is somehow like comparing apples and oranges. – TonySalimi Mar 25 '19 at 12:41
  • @Jarod42 that would be my intention with the 2nd method. Is constexpr used primarily by the compiler to substitute the value? – regomodo Mar 25 '19 at 13:16
  • 1
    Similar question: [constexpr vs static const](https://stackoverflow.com/questions/41125651/constexpr-vs-static-const-which-one-to-prefer). – 1201ProgramAlarm Mar 25 '19 at 14:45
  • cheers @1201ProgramAlarm. The answer by AnT was useful – regomodo Mar 25 '19 at 16:29

1 Answers1

1

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;
Jarod42
  • 203,559
  • 14
  • 181
  • 302