Tuesday 3 July 2012

define and const

const identifiers are often better than #define because:
  • they obey the language's scoping rules
  • you can see them in the debugger
  • you can take their address if you need to
  • you can pass them by const-reference if you need to
  • they don't create new "keywords" in your program.
In short, const identifiers act like they're part of the language because they are part of the language. The preprocessor can be thought of as a language layered on top of C++. You can imagine that the preprocessor runs as a separate pass through your code, which would mean your original source code would be seen only by the preprocessor, not by the C++ compiler itself. In other words, you can imagine the preprocessor sees your original source code and replaces all #define symbols with their values, then the C++ compiler proper sees the modified source code after the original symbols got replaced by the preprocessor.
There are cases where #define is needed, but you should generally avoid it when you have the choice. You should evaluate whether to use const vs. #define based on business value: time, money, risk. In other words, one size does not fit all. Most of the time you'll use const rather than #define for constants, but sometimes you'll use #define. But please remember to wash your hands afterwards.
//----------------------------------------------------------code-----------------------------------------------------------
Output ?
Output ?
Output ?

Output ?

Output ?
//---------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment