-2
#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)

2
  • 3
    These things are addressed by any C programming book ever written when they explain the preprocessor. Claiming that your compiler has bugs when you haven't even read the pre-processor chapter in a beginner-level book is very arrogant. Commented Sep 11 at 6:48
  • @peter Rather than update your post with a potential answer, rollback your edit and review What should I do when someone answers my question?. You may even self-answer your own question. As is, the edit (b/n-a/n) itself is a weak suggestion and may attracts DVs. Commented Sep 11 at 10:04

1 Answer 1

5

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

May want to suggest the OP get their compiler to output the preprocessed file using something like gcc -E.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.