Search code examples
cpost-incrementlanguage-concepts

Why does the value of i not increment for i=i++; statement?


Code:

for(int i=0;i<5;){
  i=i++;
  printf("%d",i);
}

The above program print zeros infinitely, How is that possible? There is the statement i=i++;. Please explain why the value of i do not increment.


Solution

  • The statement i = i++ is undefined behaviour in C. Simplistically, modifying and using the same object without an intervening sequence point is not guaranteed to work in any way you expect.

    Sequence points are covered in Appendix C of the ISO C standard if you're interested in an in-depth investigation. Basically, they consist of:

    • Between the evaluations of the function designator and actual arguments in a function call and the actual call.
    • Between the evaluations of the first and second operands of the following operators: logical AND &&; logical OR ||; comma ,.
    • Between the evaluations of the first operand of the conditional ?: operator and whichever of the second and third operands is evaluated.
    • The end of a full declarator.
    • Between the evaluation of a full expression and the next full expression to be evaluated. The following are full expressions: an initializer that is not part of a compound literal; the expression in an expression statement; the controlling expression of a selection statement (if or switch); the controlling expression of a while or do statement; each of the (optional) expressions of a for statement; the (optional) expression in a return statement.
    • Immediately before a library function returns.
    • After the actions associated with each formatted input/output function conversion specifier.
    • Immediately before and immediately after each call to a comparison function, and also between any call to a comparison function and any movement of the objects passed as arguments to that call.