Monday, May 24, 2010

C++ programming question?

Can someone give me one reason or two for using a #define to define a constant

C++ programming question?
In C++ there is no good reason and a number of reasons why you should not do it.





If this is a question from an instructor, he doesn't really know C++ but is probably looking for (a) all changes to the constant can be made in one place so helps maintainability and (b) #defines are usually coded as upper case by convention and therefore easy to find and identify as constants.





All of these things can be similarly accomplished by Sy's suggestion to use a const variable or enum, although there is no need to make it static.
Reply:No, there are no good reason to use #define to define a constant in C++. Values #defined is not type-checked by your compiler because #define is processed by preprocessor. You should use static const value or enum to define a constant.





Unless you're writting C code, than #define can help readablility.
Reply:a) It may improve readability.


#define EARTHGRAVITY (9.8)





Seeing a "9.8" in your code might be less meaningful to someone other than you.





b) You may change your mind later.


#define EARTHGRAVITY (9.80665)





Now, wasn't changing that one define a lot easier than searching and replacing all the 9.8 in all your 100,000 lines of code and 30 source files?


No comments:

Post a Comment