HiveBrain v1.2.0
Get Started
← Back to all entries
principlecppCritical

'static const' vs. '#define'

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
defineconststatic

Problem

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[]) {
...
}

Code Snippets

namespace {
   unsigned const seconds_per_minute = 60;
};

int main (int argc; char *argv[]) {
...
}

Context

Stack Overflow Q#1637332, score: 159

Revisions (0)

No revisions yet.