increment difference

  • Thread starter Thread starter vinnie
  • Start date Start date
Vinnie --

++i = pre-statement increment and
i++ = post-statement increment

When used as a statement by itself the effective difference is none.

i.e.

int i = 0;
++i; // i = 1

and

int i = 0;
i++; // i = 1

both result in i being incremented by 1 and the resulting value is 1.

However when used in a more complex statement the position of the ++ can
make a difference.

The following statement results in the 2nd array value being assigned to x
because i is incremented before the assignment to x takes place.

int i = 0;
int[] a = { 1, 2, 3 };
int x = a[++i]; // x = 2; i is incremented pre-statement (before execution
of the statement).

....

In this case however the 1st array value is assigned to x because i is
incremented after the assignment to x takes place.

int i = 0;
int[] a = { 1, 2, 3 };
int x = a[i++]; // x = 1; i is incremented post-statement (after execution
of the statement).

HTH
 
what's the difference between " i++ " and " ++i " ?

Thanks

Assuming the appropriate declarations, then

i = 1;
x = i++;

assigns 1 to x -- "++" is post-increment operator.

i = 1;
x = ++i;

assigns 2 to x -- "++" is pre-increment operator.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top