What is the difference between #define and const? And when do you use which?
What is the difference between #define and const? And when do you use which?
a #define is handled by the preprocessor, which mashes up source files for the compiler to handle beforehand. const are like variables, but have a constant value. you can't use const to make macros such as
#define MACRO(x) { x += 10 };
if you wait, somebody will probably give a better answer. www.google.com would probably give the best answer of all.
.sect signature
This as an incomplete answer but might help.
#define is a preprocessor facility used in C to define constants and macros among other things. The preprocessor goes through the source file and does a literal replacement of the values defined. In C a const only prevents the program from changing the value of the const variable.
In C++ a const is used as a preprocessor tool instead of a #define. It lets the programmer "type qualify" the variable where #define cannot do that. Ex. #define number 33 vs. const int number = 33;
There is a lot more to this. Check a good book on C/C++.
rc7j
If you use #define, this will be processed by the preprocessor. So when you define
#define MY_VALUE 10
then everywhere in the code MY_VALUE appears, it is substituted by 10. But if you declare a const, you declare a constant variable and a variable takes memory. A constant variable can be used in almost the same way as a normal variable, but its value can't be changed. A defined value can't be used as a variable.
One key difference between using preprocessor defines and constants is type checking. I'll take compile-time warnings over run-time errors anyday :)
Jason Deckard