x++
and ++x
both add 1
to x
. The only difference between them is the value of the expression itself, e.g. if you do:
y1 = x++;
or
y2 = ++x;
y1
will get the old value of x
, while y2
will get the new value of x
. See What is the difference between i++ and ++i?.
Since you don't assign the result of the expression to anything, the difference is irrelevant in your program. If you had written:
sum = sum + ++x;
you would get a different result than
sum = sum + x++;
since now you're using the value of the expression, and the result matters.
Regarding your second question, statements are executed in order. So if you put ++x;
before the assignment, then you'll be adding the incremented values of x
to sum
instead of the original values. Instead of adding 1
, 2
, 3
, ... 10
, you'll add 2
, 3
, 4
, ..., 11
. You can see this difference if you put:
printf("Adding %d + %d\n", sum, x);
before the assignment.
Putting the increment statement before or after the assignment is similar to using the increment expression in the assignment itself, and choosing between pre-increment and post-increment. I.e.
++x; // or x++;
sum = sum + x;
is the same as
sum = sum + ++x;
Conversely,
sum = sum + x;
++x; // or x++;
is the same as
sum = sum + x++;