Which is the best method of storing data that doesn't change? Some people use #define and others constants. It would be good to know when to use const's or #define's.
Thanks.
Which is the best method of storing data that doesn't change? Some people use #define and others constants. It would be good to know when to use const's or #define's.
Thanks.
In C++ use const.
-Prelude
My best code is written with the delete key.
a #define is part of the preprocessor which isn't included in the compiled code. let's say you #define PI 3.1415926535876. before anything else happens, your preprocessor will replace every 'PI' with 3.1415926535876. then your compiler will do its work as usual.
a const is a constant variable. all the rules of c and c++ apply to it.
the biggest advantage to using const variables is type checking. errors are much easier to spot using a const variable than a #define. #defines also tend to mess up in unusual expressions.
in short: use a const. it gives your compiler extra information that can sometimes prevent errors (or at least make them more obvious.)
Thanks for your replies. So when I make a call, to include a #define in my code is a local variable created and then destroyed when the statement has called. Or is the variable destroyed when the program exits? e.g.
Code:#include <iostream.h> #define MAX_NUM 512 int main(void) { cout << "The maximum num is: " << MAX_NUM; getchar(); return 0; }
#define does not create any variables. The preprocessor changes
To be:Code:#include <iostream.h> #define MAX_NUM 512 int main(void) { cout << "The maximum num is: " << MAX_NUM; getchar(); return 0; }
These codes are equal to the compiler.Code:#include <iostream.h> //This is replaced by the contents of iostream.h int main(void) { cout << "The maximum num is: " <<512; getchar(); return 0; }