+ 1

Can someone please explain me how this code outputs 12 49?

#include <stdio.h> #define PRODUCT(x) (x*x) int main() { int i =3, j,k; j = PRODUCT(i++); k = PRODUCT(++i); printf("\n%d %d", j, k); return 0; }

18th Apr 2021, 3:54 PM
Sakshi
Sakshi - avatar
3 Antworten
+ 8
The important thing to understand is that macros are not functions. Macros simply paste the text you specify in place of the macro invocation. In your code, the expression PRODUCT(i++) will simply be changed to `i++ * i++` and PRODUCT(++i) will be changed to `++i * ++i` before compilation. Both `i++ * i++` and `++i * ++i` are undefined behaviour (the warnings given by the compiler are proof). So even though it can be 'almost' explained by following the code, there is no point in explaining. Just avoid using increment and decrement operations with macros like these.
18th Apr 2021, 4:16 PM
XXX
XXX - avatar
+ 2
Hi! see how your code is executed step by step: Visualize your code execution (Python, Java, C, C++, JavaScript, Ruby) https://pythontutor.com
18th Apr 2021, 4:02 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
Thanks for helping XXX
18th Apr 2021, 4:23 PM
Sakshi
Sakshi - avatar