The output is 9 49 can any1 explain how we get this output?
Code:#define P(x) (x*x) main( ) { int i=3,j,k; j=P(i++); k=P(++i); printf("\n%d %d",j,k); }
The output is 9 49 can any1 explain how we get this output?
Code:#define P(x) (x*x) main( ) { int i=3,j,k; j=P(i++); k=P(++i); printf("\n%d %d",j,k); }
i is 3, so the first one is simple: 3 * 3 is 9. x is replaced with i++, so after j=P(i++) i is 5.
The second one i is incremented twice, so k=P(++i) is 7 * 7 which is 49.
But I'm pretty sure this is undefined behaviour, so it would only explain what may have happened in this case.
Thansk i got it. The difference lies in post and pre increment operators.
But you can make no assumptions about it in this case. For example, I tried this:
And clang gave me: 12, 42Code:printf("%d %d\n", (i++ * i++), (++i * ++i) );
but gcc: 25, 25
The difference is not only in pre and post increment operators. The issue is that i is being modified multiple times without intervening sequence points. That is undefined behaviour.
If both lines computed a value of 42, the behaviour would still be correct. If the code reformatted your hard drive, the behaviour would still be correct. That is what "undefined" means in the C standard: any behaviour is allowed, and every possible behaviour is equally correct.
> The output is 9 49 can any1 explain how we get this output?
Sure -> Comma Operator - C And C++ | Dream.In.Code
You're just not going to get a consistent answer out of code like that.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.