That's not a good use of pre-increment.
If you want to look at array[i]
and array[i+1]
, just do that:
printf("%d %d\n", array[i], array[i+1]);
Remember, i++
does not just take i
's old value and add 1 to it. It takes i
's old value, and adds 1 to it, and stores the new value back into i
. When you were printing array[i]
and array[i+1]
, did you really want to change the value of i
?
If you did want to change the value of i
— or, in any case, since that mention of array[i++]
did change the value of i
— you introduced undefined behavior. Once you've got an expression that's modifying the value of i
, how do you know what array[i]
will print? How do you know that array[i]
won't end up using the new value of i
? You probably assumed that things are evaluated from left to right, but it turns out that's not necessarily true. So weird, weird things can happen.
Here's an example that helps show how ++
works, and that's well-defined:
#include <stdio.h>
int main()
{
int array[5] = {1,2,3,4,5};
int i = 1;
array[i++] = 22;
array[++i] = 44;
for(i = 0; i < 5; i++)
printf("%d: %d\n", i, array[i]);
return 0;
}
Or, as you suggested in a comment, if you did want to modify i
's value, perhaps to advance the variable i
along the array, you sometimes have to take care to move the i++
into a separate statement. The simple rule is, if you're applying ++
or --
to a variable, you can only use that variable once in the same statement. So you can't have i++ + i++
, since that has two i
's in it and they're both modified. But you also can't have i + i++
, or f(a[i], a[i++])
, since those have a spot where you modify i
, and a spot where you use i
, and there's no way to know whether you use the old or the new value of i
. (And, again, in C there's not a general left-to-right rule that helps you here.)