This is a question from kn king's c programming : a modern approach. I can't understand the solution given by him:-
The expression ++i is equivalent to (i += 1). The value of both expressions is i after
the increment has been performed.
How do I understand this anyway?
i = 10
printf("%d", i++);
will print 10, where as
printf("%d", ++i);
will print 11
X = i++ can be thought as this
X = i
i = i + 1
where as X = ++i is
i = i + 1
X = i
so,
printf ("%d", ++i);
is same as
printf ("%d", i += 1);
but not
printf ("%d", i++);
although value of i after any of these three statements will be the same.
The solution means to say that there is no difference, ++i has the same meaning as (i += 1) no matter what i happens to be and no matter the context of the expression. The parentheses around i += 1 make sure that the equivalence holds even when the context contains further arithmetics, such as ++i * 3 being equivalent to (i += 1) * 3, but not to i += 1 * 3 (which is equivalent to i += 3).
The same would not apply to i++, which has the same side effect (incrementing i), but a different value in the surrounding expression — the value of i before being incremented.
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