Here is a very simple C program:
int main()
{
int i = 0;
while(i++ < 10)
printf("%d\n", i);
return 0;
}
The result is:
1
2
3
4
5
6
7
8
9
10
Why 0
is not the first number to print?
And if I replace the i++
with ++i
I'll get this:
1
2
3
4
5
6
7
8
9
For both i++
and ++i
the first number is 1
.
I expected to see the 0
for post increment in while loop while()
.
Thanks.
Flow Chart for While loop If the condition is True, then it will execute the statements inside of it. Next, we have to use Increment & Decrement Operator inside it to increment and decrement the value.
++i : is pre-increment the other is post-increment. i++ : gets the element and then increments it. ++i : increments i and then returns the element. Example: int i = 0; printf("i: %d\n", i); printf("i++: %d\n", i++); printf("++i: %d\n", ++i); Output: i: 0 i++: 0 ++i: 2.
int n = 0 defines and initializes a local variable n of type int to the value 0 . while (n++ < TEN) : n is compared to TEN , the result is true ( 1 in C) since 0 < 10 then n is incremented and gets the value 1 . The result of the comparison is true hence the while loop proceeds to its commanded statement.
Pre increment directly returns the incremented value, but post increments need to copy the value in a temporary variable, increment the original and then returns the previous made copy.
The i++
(and ++i
) is done as part of the while
expression evaluation, which happens before the printing. So that means it will always print 1
initially.
The only difference between the i++
and ++i
variants is when the increment happens inside the expression itself, and this affects the final value printed. The equivalent pseudo-code for each is:
while(i++ < 10) while i < 10:
i = i + 1
printf("%d\n", i); print i
i = i + 1
and:
i = i + 1
while(++i < 10) while i < 10:
printf("%d\n", i); print i
i = i + 1
Let's say i
gets up to 9
. With i++ < 10
, it uses 9 < 10
for the while
expression then increments i
to 10 before printing. So the check uses 9 then prints 10.
With ++i < 10
, it first increments i
then uses 10 < 10
for the while
expression. So the check uses 10 and doesn't print anything, because the loop has exited because of that check.
i++
is post-increment and ++i
is pre-increment. Post-increment means that the previous value is returned after incrementing the object. Pre-increment means that the object is incremented and then returned. Either way, the object is incremented when its expression is evaluated and that's why you don't get 0
as the first output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With