Possible Duplicate:
static const vs #define
In C++, to define a constant to be used across the entire application, what is the usual practice?
#define WINDOWS_HEIGHT 1024
or
const int WINDOWS_HEIGHT = 1024;
Possible Duplicate:
static const vs #define
In C++, to define a constant to be used across the entire application, what is the usual practice?
#define WINDOWS_HEIGHT 1024
or
const int WINDOWS_HEIGHT = 1024;
Using enum
and not to worry about linkage.
Pros and cons to everything, depending on usage:
template <typename T> void f(T t) { cout << ++t; }
won't compile)template <typename T> void f(T)
get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation.#define X "x"
and some client usage ala "pre" X "post"
, you're in trouble if you want or need to make X a runtime-changeable variable rather than a constant, whereas that transition is easier from a const char*
or const std::string
given they already force the user to incorporate concatenation operations.{ 1, 2 }
that can be used to initialise arrays, or #define MICROSECONDS *1E-6
etc. (definitely not recommending this!)__FILE__
and __LINE__
can be incorporated into the macro substitutionAs a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).
Hmm, it depends. For integer constants, enum
works great. Something like:
struct Constants {
enum {
WindowHeight = 8,
WindowWidth = 8,
// ...
};
};
...
int h = Constants::WindowHeight;
Use the constant integer; it will show up in the debugger where that #define value may not. Or use an enum; that works too.
My vote is for a 'namespace scope extern const' variable defined in one and only one translation unit. Namespace scope 'const' variables have internal linkage.
Using a define simply replaces all occurrences in your code with that value. A const global variable is nearly the same; only the type can be explicitly defined. This is pretty much the only difference.
Personally, I would prefer to use a define, just out of taste.
But, again, I don't think there is any difference.