Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • 24
    Scott Meyers covers this subject very nicely and thoroughly. His Item#2 in "Effective C++ Third Edition". Two special cases (1) static const is preferred within a class scope for class specific constants; (2) namespace or anonymous scope const is preferred over #define. Commented May 18, 2011 at 1:48
  • 3
    I prefer Enums. Because it is hybrid of both. Doesn't occupy space unless you create a variable of it. If you just want to use as a constant , enum is the best option. It has type safety in C/C++11 std and also a perfect constant. #define is type unsafe , const takes space if compiler can't optimize it. Commented Jul 1, 2013 at 6:54
  • 2
    My decision whether to use #define or static const (for strings) is driven by initialization aspect (it was not mentioned through the answers below): if constant is used within particular compilation unit only, then I go with static const, else I use #define - avoid static order initialization fiasco isocpp.org/wiki/faq/ctors#static-init-order Commented Feb 3, 2017 at 9:08
  • 1
    If const, constexpr or enum or any variation works in your case, then prefer it to #define Commented Aug 28, 2017 at 23:47
  • @MartinDvorak "avoid static order initialization fiasco" How is that a problem for constants? Commented Jun 15, 2018 at 17:57