I have a piece of code like this:
/* T matrix */
#define T11 0
#define T12_re 1
#define T12_im 2
int main(int argc, char *argv[])
{
return 1;
}
my question is why did it use preprocessor directives to define global variables and did not simply used a code like this:
/* T matrix */
double T11 = 0;
double T12_re = 1;
double T12_im = 2;
int main(int argc, char *argv[])
{
return 1;
}
Preprocessor symbols are not variables. In your first code, T13_im
(etc...) is not a variable (but a preprocessed name, expanded to 4
at parsing time)
In your second code (it does not compile as you wrote it), you might have
const double T12_re= 1.0;
Then you have declared a variable T12_re
of const double
type.
Read the wikipage on the C preprocessor, the documentation of GNU cpp and realize that the compiler sees only the preprocessed form; for your file yoursource.cc
you could get the preprocessed form yoursource.ii
using the command g++ -Wall -C -E yoursource.cc > yoursource.ii
then use a pager or editor to glance inside the generated yoursource.ii
Sometimes, the preprocessor permits cute tricks like this. And you cannot always use variables. For instance, the case
expression should be a compile-time constant and cannot be in C a const int
variable. (You could use some enum
, and it is different in C and in C++).
The definitive answer to your question why is not possible - there is no reason to use obsolete constructs like those #define
s. The main reason is that in the old times this was the only way to define constants (because we are talking about constants not variables. So the main reason is lack of knowledge.
Don't use such constructs - use proper C++ constants, like
const double T12_re = 0.1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With