0

I'm a beginner in programming and I have a question. Mainly, what is the difference in defining PI exactly as I state below;

#define PI  (4.*atan(1))
#define PIa  4.*atan(1)
#define PIb  4*atan(1)

I have printed this code:

    printf( "%lf\n", 3 / PI );
    printf( "%lf\n", 3 / PIa );
    printf( "%lf\n", 3 / PIb );

The results are:

 0.954930
 0.589049
 0.000000

According to my calculator the first one is correct, and the rest should also be. Why aren't they?

Dylikk
  • 25
  • 3
  • 3
    The difference is in the literal expansion of the macros. `3 / PIb` will become `3 / 4*atan(1)` - and here the first operation is *integer division* `3/4`, which is giving `0`. In `3 / PIa` the expansion leads to division to be carried out first too, which is not the correct order of operations. – Eugene Sh. Oct 14 '21 at 15:58
  • I would include math.h and use `M_PI` – stark Oct 14 '21 at 16:42

1 Answers1

2

The macro is text substitution thus:

3 / PIa 

is parsed as:

3 / 4.*atan(1) = (3/4.) * atan(1)

This is different from the first case where 3 / PI is expanded as:

3 / (4.*atan(1))

The similar case is for the third example:

3 / 4*atan(1) = (3/4) * atan(1)

The expression 3/4 is integer division, which result is 0.

Generally, it is strongly advised to put parentheses around the whole macro and all parameters it takes like in the following example:

#define ADD(a,b) ((a) + (b))
tstanisl
  • 13,520
  • 2
  • 25
  • 40