Possible Duplicate:
C++ - enum vs. const vs. #define
Before I used #define
I used to create constants in my main function and pass them where they were needed. I found that I passed them very often and it was kind of odd, especially array sizes.
More recently I have been using #define
for the reason that I don't have to pass constants in my main to each individual function.
But now that I think of it, I could use global constants as well, but for some reason I have been a little hesitant towards them.
Which is the better practice: global constants or #define
?
A side question, also related: Is passing constants from my main as I described a bad practice?
They don't do quite the same thing. #define
lets you affect the code at compilation time, while global constants only come into effect at runtime.
Seeing as #define
can only give you extra trouble because there's no checking going on with how you use it, you should use global constants when you can and #define
when you must. It will be safer and more readable that way.
As for passing constants from main
, it's not unreasonable because it makes the called functions more flexible to accept an argument from the caller than to blindly pull it out of some global. Of course it the argument isn't really expected to change for the lifetime of the program you don't have much to gain from that.
Using constants instead of #define is very much to be preferred. #define replaces the token dumbly in every place it appears, and can cause all sorts of unintended consequences.
Passing values instead of using globals is good practice. It makes the code more flexible and modular, and more testable. Try googling for "parameterise from above".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With