Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use pre processor directives to define variables?

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;
}
like image 424
Sepideh Abadpour Avatar asked Oct 31 '22 12:10

Sepideh Abadpour


2 Answers

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++).

like image 129
Basile Starynkevitch Avatar answered Nov 15 '22 04:11

Basile Starynkevitch


The definitive answer to your question why is not possible - there is no reason to use obsolete constructs like those #defines. 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;
like image 39
Wojtek Surowka Avatar answered Nov 15 '22 05:11

Wojtek Surowka