principlecppCritical
'static const' vs. '#define'
Viewed 0 times
defineconststatic
Problem
Is it better to use
What are advantages/disadvantages for each method?
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
The main advantage to a
Advantages of "
I don't know exactly what you are getting at with the "
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 examplenamespace {
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.