-
Constants
i have defined constants in a header file
//Define constants
#define Grids 70
#define Hori_L 1.0
#define delta_x Hori_L*pow((Grids - 1), -1) //m
However when i call them in my .cc files I need to place a bracket around them (delta_x). Why is that?
Cheers
-
-
What happens when you use constants without brackets? What error messages do you get?
If only the third one is the problem:
Code:
#define delta_x Hori_L*pow((Grids - 1), -1) //m
Then you need to remove the comment from it because it may cause problems like this:
Code:
#define Grids 70
#define Hori_L 1.0
#define delta_x Hori_L*pow((Grids - 1), -1) //m
int main(int argc, char **argv) {
printf("%d\n", delta_x);
return 0;
}
will become this after preprocessing:
Code:
#define Grids 70
#define Hori_L 1.0
#define delta_x Hori_L*pow((Grids - 1), -1) //m
int main(int argc, char **argv) {
printf("%d\n", Hori_L*pow((Grids - 1), -1) //m);
/*notice that the end of the statement gets cut off*/
return 0;
}
and you should have brackets around that anyway, so that the order of operations doesn't get messed up
it should look like this:
Code:
#define delta_x (Hori_L*pow((Grids - 1), -1))
-
you could add C-style comments and be ok.
Code:
#define delta_x (Hori_L*pow((Grids - 1), -1)) /*m*/
-
you should use const int or const double in C++
-
For one thing, I note that x to the power of -1 is actually 1/x. So the expression:
Code:
Hori_L*pow((Grids - 1), -1)
can be simplified to:
Code:
Hori_L / (Grids - 1)
Then as vart suggested, you should prefer const to #define here, so it would be:
Code:
const int Grids = 70;
const double Hori_L = 1.0;
const double delta_x = Hori_L / (Grids - 1);
-
> However when i call them in my .cc files I need to place a bracket around them (delta_x). Why is that?
Because #define is just a dumb search/replace operation.
Eg.
#define ADD(x,y) x + y
Then you do
x = ADD(1,2) * ADD(3,4);
What the compiler sees is
x = 1 + 2 * 3 + 4;
At which point, the precedence is all screwed and you end up with something completely different to what you intended.
Anything more complicated that a simple constant should have () around the whole thing to prevent any kind of precedence mishap later on.