Solved Why the C language outputs are not as I think?

May 7, 2018 at 06:09:12
Specs: Windows 7, i5 2520M / 8 GB
I am a beginner for C language, I get a sample C program as below:
--------------------
#include <stdio.h>
#define SQUARE (X) X*X
#define PR(X) printf("macro is %d\n", X)
main()
{ int A=4;
PR(SQUARE(A)); -- original answer is 16. It's same as mine.
PR(SQUARE(A+2)); --original answer is 14. but my output is 36.
PR(SQUARE(++A)); -original answer is 36, but my output is 25
PR(100/(SQUARE(2));-original answer is 100, but my output is 25
}
--------------------

the final outputs are not as I think. Could anyone why? or the original answers are wrong. Thanks!!


See More: Why the C language outputs are not as I think?

Reply ↓  Report •

#1
May 7, 2018 at 07:57:18
Your outputs are correct.

So what are these "original answers"?


Reply ↓  Report •

#2
May 7, 2018 at 08:24:55
✔ Best Answer
Presumably "original answer" -> what the program gives, and "my output" -> what the OP thinks the answer should be.

The C / C++ preprocessor just does a find & replace. So after going through the preprocessor, your main() becomes:

main()
{ int A=4;
printf("macro is %d\n", A*A); -- original answer is 16. It's same as mine.
printf("macro is %d\n", A+2*A+2); --original answer is 14. but my output is 36.
printf("macro is %d\n", ++A*++A); -original answer is 36, but my output is 25
printf("macro is %d\n", 100/2*2);-original answer is 100, but my output is 25
}

So the first's result is as you expected.
The second one follows order of operations, and you have 4+8+2 = 14.
I believe the third attempt is undefined, so you get whatever the compiler wants to give you.
The final case has the division and multiplication cancel each other out.

How To Ask Questions The Smart Way


Reply ↓  Report •

#3
May 8, 2018 at 00:36:28
thank you for your assistance.
Could you explain more about ++A*++A. I am little confused.
wangw

Reply ↓  Report •

Related Solutions

#4
May 8, 2018 at 09:03:18
I don't normally deal in C/C++, so I'm not exactly the best resource on sequence points. Basically, all side effects (such as incrementing A from the ++A) must occur within a certain window, but it can happen at any time within that window. In your case, the only two guarantees you have is 1) two ints will be multiplied together, resulting in an int; 2) by the time you execute printf(), A == 6. To be honest, I'm not even sure that second guarantee exists.

Best explanation I've seen comes from this Stack Overflow question, which also tells me sequence points are no longer called "sequence points," but that the behavior is mostly the same.

Your SQUARE(X) could definitely use some work, and you could eliminate the wrong answers you're seeing for cases 2 and 4, but the third case will never be well defined. So the real takeaway from this thread is to use functions instead of macros.

How To Ask Questions The Smart Way

message edited by Razor2.3


Reply ↓  Report •

Ask Question