0

Why $a++ and ++$a gives same result in for loop?

for loop no difference with post or preincrement

6th Dec 2017, 1:49 PM
Boris
Boris - avatar
1 Answer
+ 4
After evaluating $a++ or ++$a,the new value of i will be the same in both cses. The difference between pre- and post-increment is in the result of evaluating the expression itself. ++$a increments i and evaluates to the new value of i. $a++ evaluates to the old value of i, and increments i. The reason this doesn't matter in a for loop is that the flow of control works roughly like this: 1)test the condition 2)if it is false, terminate 3)if it is true, execute the body 4)execute the incrementation step Because (1) and (4) are decoupled, either pre- or post-increment can be used for(i=0; i<5; i++) { printf("%d", i); } and for(i=0; i<5; ++i) { printf("%d", i); } when the semantics of for loop is same like above for loop then it does same effect on the loop and semantics are different then ++I and i++ have not give same output like int i = 0; int j = i; while(j < 5) { printf("%d", i); j = ++i; } and int i = 0; int j = i; while(j < 5) { printf("%d", i); j = i++; }
6th Dec 2017, 2:14 PM
GAWEN STEASY
GAWEN STEASY - avatar