0

I have a class source file Foo.cpp and I need to define IntVal constant only for local use by class methods.

// Option 1
const int IntVal = 5;
// Option 2
static const int IntVal = 5;
// Option 3
namespace {
        const int IntVal = 5;
}

int Foo::GetValue()
{
        return this->value + IntVal;
}

Which one is preferred?

4
  • 2
    If it's supposed to belong to the class, you can make it a static class member. If it's just used for the implementation, option 3 is the modern way to represent something only used only in a single translation unit. Commented Jul 6, 2021 at 21:13
  • 2
    constant only for local use by class methods Inside the class, add: constexpr static some_type some_name = some_value; Commented Jul 6, 2021 at 21:13
  • 3
    or just constexpr some_type some_name = some_value;
    – Ted Lyngmo
    Commented Jul 6, 2021 at 21:37
  • 1
    const objects defined at file scope are by default static, so Option 1 and Option 2 are the same. Commented Jul 6, 2021 at 21:57

1 Answer 1

1

For hardcoded constants like that, I'd pretty much always go with:

static constexpr int kIntValue = 5;

If I had to bet, I'd say all of those compile to almost exactly the same code though (unless you're trying to use the number in a constexpr context) so it probably comes down to personal preference/style.

Not the answer you're looking for? Browse other questions tagged or ask your own question.