#include <stdio.h>
#define n 16
#define a -2.0
#define b 2.0
#define c (b-a)/n
int main() {
printf("%lf\n",5.0*c);
}
Outputs 1.250000
But if i change (b-a)/n to b/n-a/n it outputs 0.750000.
#include <stdio.h>
#define n 16
#define a -2.0
#define b 2.0
#define c b/n-a/n
int main() {
printf("%lf\t%lf\n",c,5.0*c/5.0);
}
Outputs 0.250000 0.650000
So if i print c alone it's correct, but if i actually perform some operation with it, it turns out that c is different.
Update: It seems to require the expression to be in parentheses. (b/n-a/n)
It's not a bug. Macros perform direct token substitution. So this:
printf("%lf\t%lf\n",c,5.0*c/5.0);
Expands to this:
printf("%lf\t%lf\n",2.0/16 - -2.0/16,5.0*2.0/16 - -2.0/16/5.0);
This demonstrates why identifiers in macros should always be parenthesized:
#define c (((b)/(n))-((a)/(n)))