division by directive

Jul 29, 2010 at 1:16pm
hy guys.

I have defined in my code the following:

1
2
#define SIGMA 6.25;
#define XBOXSIZE 2*SIGMA; 


and later, I use

1
2
double a = XBOXSIZE
cout << a/XBOXSIZE;


The answer I get is 39.0625 and not 1. Why is that? I was sure that the #define is supposed to replace any occurrence in the code of XBOXSIZE with 12.5 because:
XBOXSIZE = 2*SIGMA = 2*6.25 = 12.5

thanks.
Jul 29, 2010 at 1:19pm
1
2
cout << a/XBOXSIZE
cout << a/2*SIGMA // 2*6.25/2*6.25 = 12.5/2*6.25 = 6.25*6.25 = 39.0625 


solution:
#define XBOXSIZE (2*SIGMA)
Last edited on Jul 29, 2010 at 1:23pm
Jul 29, 2010 at 1:28pm
Much better solution:

1
2
const double SIGMA=6.25;
const double XBOXSIZE=2*SIGMA;
Jul 29, 2010 at 1:45pm
Skillless Thanks.

Athar, to my understanding, the use of directive should be faster as they are numbers and not memory addresses. isn't it so?
Jul 29, 2010 at 1:52pm
No. Constant folding can be applied as long as the constant definition is visible to the compiler.
Jul 29, 2010 at 2:50pm
Thanks, I still think that I need to use it as the value of BOXSIZE as well as many other values should be available to other classes in the code
Jul 29, 2010 at 2:53pm
What does that have to do with anything?
Constants aren't limited to a class.
Jul 29, 2010 at 3:10pm
They are if they are not global. I got mixed up with how to define global variable and I don't want to dive into that now.

There is a good change I haven't fully understood the global concept, that's why I'm posting in the beginner forum but, as I'm not doing my Ph.D. on computer programming but on physics, I don't want to spend time on that know. I will probably, do this later on in my research
Jul 29, 2010 at 6:53pm
define variable outside of function -> global
define variable inside of function -> local
Topic archived. No new replies allowed.