-
const vs. #define
One C++ programming book I have said that it's a better idea to use
const type x = value;
than
#define x value
Is there any truth to this? Which do you use?
I can think of two conceivable reasons to use const:
Constants have a type, which is important in a strongly typed language like C++.
Const may only need to be written into the program once. Not quite sure about this one, but it's possible that when using const, the compiler can use the same copy of the constant multiple places within the program.
Anybody have any useful information on this?
-
I use const all the time..... in fact I only really use #define for inclusion guards or conditional compilation. I prefer inline functions to macros. I know some functions wont be inlined that would be had i used a macro but i guess that if the function doesn't get inlined then it shouldn't be inlined anyway.
-
They are nearly the same thing. The #define is global, the other is not.
-
I use enums for integer type values, because I can keep it local to the
class.
You sometimes get the problem
Code:
class C {
public:
private:
// want a constant local to the class
static const int num = 4;
enum {
NUM = 4
};
};
Outside of classes, most c++ people will tell you to use const.
Thinking in c++ gives a very pretty good explanation of this.
-
though they say one is better... i belive this is untrue since both have valid purposes use what fits the situation.
-
Summary...
This is my personal preference for using constants:
Const:
Numerical constants and similar
Why?
Strong typechecking.
Can limit scope of const. ( to eg. a function )
Enum:
Logical grouping of numerical constants
enum fruit { apple, orange, pear }
'Selection' parameter to function.
myFunc( fruit selectFruit );
Why?
Again typechecking, (compare to myFunc( int selectFruit) )
#define:
Preprocessor related paramer settings
With #include to avoiding double codeinclution.
Why?
There is no other nice way to do it, (to my knowlege).
If you can think up any objections I would be glad to hear them..
- Anders