0

So here is the question in my book, I have to tell the output.

#include <stdio.h>
#define prod(x) (x*x)
int main() {
    int i=3,j,k,l;
    j=prod(i+1);
    k=prod(i++);
    l=prod(++i);
    printf("i=%d\tj=%d\tk=%d\tl=%d",i,j,k,l);
    return 0;
}

The answer is in book is :

i=7     j=7     k=9     l=49

I get the part why i=7 and j=7 but how is k=9 and l=49.

Also when i run in visual studio community i get the same output but when i run it on an online compiler i get

i=7     j=7     k=12     l=49

Can someone tell me why is this happening?

Virat
  • 77
  • 7
  • The macro should be `#define prod(x) ((x)*(x))` with more parentheses. But it generates undefined behaviour, please see [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior) – Weather Vane Oct 08 '22 at 18:57
  • Throw the book in the bin. Or burn it. – Weather Vane Oct 08 '22 at 19:02
  • *Can someone tell me why is this happening?* Because the book was written by someone who doesn't know C. It's good that you asked about this wrong bit, but there are probably many other misguided things that this book is "teaching" you, that you haven't asked about yet, that are equally wrong. – Steve Summit Oct 08 '22 at 19:11
  • the book is "Let us C", I dunno my teacher told me this was the best for begginers. – Virat Oct 08 '22 at 19:15
  • The `prod` macro is broken in two different ways. Please see [question 10.1](https://c-faq.com/cpp/safemacros.html) in the [C FAQ list](https://c-faq.com/cpp/safemacros.html). The `prod` macro, as shown, follows the first of the rules listed there, but not the second or third. – Steve Summit Oct 08 '22 at 19:17
  • Yes, we've heard about *Let Us C* here before. It sounds like utter garbage. I don't know why anyone recommends it, unless they don't know C, either. We discussed this book at least once, at [this deleted question](https://stackoverflow.com/questions/58114529). – Steve Summit Oct 08 '22 at 19:20

0 Answers0