1
#include<stdio.h>
#define CUBE(X) (X*X*X)

int main()
{
int a, b;
b = 3;
a = CUBE(++b);

printf ("a = %d b = %d", a, b );
return 0;

}

How CUBE(++b) giving 150 as an output instead CUBE(++b * ++b * ++b) should be 4 * 5 * 6 = 120. Anyone please explain this

Learner_1
  • 17
  • 2
  • 3
    Does this answer your question? [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) – Gerhardh Dec 09 '21 at 08:45
  • 3
    Generally you should enclose your parameters in brackets when you use them in a macro like this: `((X)*(X)*(X))`. In this case it will not change the result. – Gerhardh Dec 09 '21 at 08:46
  • 2
    There's also other problems with your macro. Try e.g. `CUBE(1 + 2)` and see it fall apart. Solution presented in the last comment by @Gerhardh. – Some programmer dude Dec 09 '21 at 08:47

1 Answers1

2

Every parameter of a function-like macro should always be surrounded by parenthesis (as surely mentioned in the macro chapter of any C programming book):

#define CUBE(X) ((X)*(X)*(X))

As for your specific example, it holds undefined behavior, because the macro expands to ++b * ++b * ++b which is broken code with no deterministic result. See this for details: Why can't we mix increment operators like i++ with other operators?

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Macros are not always used as expressions, so the advice to always surround parameters with parentheses is not only incorrect, it is impossible. – Eric Postpischil Dec 09 '21 at 10:04
  • @EricPostpischil This is addressed to someone who has never used macros before. For beginners, the rule of thumb to always use parenthesis works just fine. They won't be doing more advanced macros passing pp constants around etc. – Lundin Dec 09 '21 at 10:53