Rtucan
Rtucan

Reputation: 157

increment two indices at once

lets say I have two int arrays, array1 and array2.

Is this line:

array1[i++] = array2[j++];

equal to this:

array1[i] = array2[j];
i++;
j++;

?

Upvotes: 2

Views: 86

Answers (2)

Bathsheba
Bathsheba

Reputation: 234655

Yes they are equivalent, unless you've written #DEFINE i j or #DEFINE j i, in which case the behaviour of the first snippet is undefined.

Upvotes: 3

dbush
dbush

Reputation: 223699

Yes, this is allowed. You're not modifying the same variable twice in one statement without a sequence point, so you're fine.

If you did this however, you'd invoke undefined behavior:

array1[i++] = array2[i++];

But this would be fine, since the comma operator introduces a sequence point:

array1[i++] = (j++,j++);

Upvotes: 2

Related Questions