rohit wrote:
> #include <stdio.h>
> #define PRODUCT(x) (x*x)
Should be ((x)*(x)) - consider the argument `i + 1`.
Actually, more like "should be `int product(x) { return x*x; }`.
> int main()
> {
>
> int i =3,j,k;
> j = PRODUCT(i++);
BOOM.
> k = PRODUCT(++i);
>
> printf("\n%d %d", j,k);
>
> return (0);
> }
>
> -----------------------------------------------------------
> The output is 9 and 49
>
> shouldn't the answer be 12 and 20?
This a FAQ, so see the C FAQ, eg
http://www.faqs.org/faqs/C-faq/faq/
question 3.2
> What are the steps the compiler takes to reach the above given output?
It compiles code for `i++ * i++` assuming that you know what you're
doing. So, at a guess, it multiples i (3) by i (still 3) to get 9.
The it increments i, possibly twice.
The it compiles code for `++i * ++i` ATYKWYD. At a guess, it increments
i, probably twice, then multiplies i (7) by i (still 7) to get 49.
The compiler-writer of course could do things differently. They could
keep a flag for each variable, "increment pending". Then `i++` compiles
as "get the value of i and set the flag", and ";" compiles as "increment
all variables with the flag set, and clear it"; and "++i" compiles as
"increment i, and return the new value". In that case, you'd
get the results 9 and 20.
Or they could compile `i++` as "if the flag is set, report a problem,
plant code to quit the program; otherwise, get the value of i and
set the flag."
--
Chris "sparqling" Dollin
"Who do you serve, and who do you trust?"