I was just thinking about some code I had written where I used the #define directive to make musical note names their own frequency. e.g.
1 2
#define C0 16.35
#define C1 32.70
I started thinking about that, and should I be doing this, or using const int? Which also spawned more questions. Like, what values should be used with #define, and which ones should be declared as a constant? I know you should use constants if it is a variable that does calculations within itself or something, like
I started thinking about that, and should I be doing this, or using const int?
You should be using const int.
what values should be used with #define,
Very little. You should only declare constants that way if you need to check the value during pre-compilation. ie: if it's going in an #if statement. Note that #if is different from if:
1 2 3 4 5 6 7
#define FOOBAR 15
#if FOOBAR == 15
// ... code here
#else
// ... code here
#endif
That is the only time you should use a #define this way. Note that such a situation is typically only used for platform-specific conditional compiling and the like. It's very rare outside of that kind of thing.
So yeah, basically... just avoid using #define unless you have to. #defines destroy scoping rules and add all sorts of other complications.
Actually if it is a legacy program, there is no need to do large amount of editing. For new program, then yes use const keyword but old habits die hard. Sometimes I still revert to use #define :P
Ah, thanks for clearing that up. Time to do a large amount of editing, haha.
Time to replace all those evil preprocessor macros with global constant variables! Which are typesafe, just in case you forget what you wanted to use them for.