Search code examples
c++cconstants

'static const' vs. '#define'


Is it better to use static const variables than #define preprocessor? Or does it maybe depend on the context?

What are advantages/disadvantages for each method?


Solution

  • Personally, I loathe the preprocessor, so I'd always go with const.

    The main advantage to a #define is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.

    Advantages of "const"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.

    I don't know exactly what you are getting at with the "static" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static. For example

    namespace {
       unsigned const seconds_per_minute = 60;
    };
    
    int main (int argc; char *argv[]) {
    ...
    }