What will be output of following program and how?

I=4;
j=++i*++i;
printf("%d", j);
My Ans-30;

Showing Answers 1 - 3 of 3 Answers

The answer can quite literally be anything. C does not force left-to-right evaluation of arithmetic expressions, nor does it require that the side effect of the ++ or -- operators be applied immediately after evaluation. The expression could be evaluated as 5 * 5, or 5 * 6, or 6 * 6, or something else entirely. You *may* get the answer you expect (30). You may get something else.
If you try to update an object more than once (like i++ * i++, or a = a++, or something similar) or if you try to update an object and use its value in a computation (like a[i] = i++) without an intervening *sequence point*, then the behavior is *undefined* - the language does not specify what the result should be.
A sequence point is a point in the evaluation where all expressions have been evaluated and all side effects have been applied. This occurs at the end of a statement, or at any of the &&, ||, ?:. or comma operators (which is not the same thing as the comma that separates arguments in a function call). So while the behavior of x++ * x++ is undefined, the behavior of x++ && x++ is well-defined - the left x++ will be evaluated first, and its side effect (increment by 1) will be applied. If the result of the evaluation is non-zero, then the right x++ will be evaluated.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions