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
Difference between both are: ++ is a unary operator while + is a binary operator....
If we consider execution time: i++ is more faster than i=i+1.
No of machine cycles differs to execute the same set of code, thats the reason ++ operators are always prefered for Loops.
Refer to this thread for more info
I think they are totally the same. There is one thing maybe interesting. The ++i is equal to (i+=1) but not i+=1; The difference is the brace. Because i += 1 may depend on the context and it will have different interpretation.
In a normal operation without assignation:
++i and i++
increase the variable in 1. In pseudo assembly both code it is:
inc i
but If you assign the value the order of ++ is relevant:
x = i++
produce:
mov x, i
inc i
x = ++i
produce:
inc i
mov x, i
In the case of: i += 1
it will produce:
add i,1
but because compilers optimize the code it also will produce in this case:
inc i
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.
One difference that has not been brought up so far is readability of code. A large part of loops use increment by one and common practice is to use i++/++i when moving to the next element / incrementing an index by 1.
Typically i+= is used in these cases only when the increment is something other than 1. Using this for the normal increment will not be dangerous but cause a slight bump in the understanding and make the code look unusual.
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.