1

Can someone explain array[++index] vs array[index++]?

I am reading a data structure book and it seems like this notation does have a difference.

mort
  • 12,118
  • 14
  • 47
  • 95

6 Answers6

5

array[++index] will first add 1 to the variable index, and then gives you the value;
array[index++] will give you the value at index, and then increment index.

General Grievance
  • 4,259
  • 21
  • 28
  • 43
Jens
  • 63,364
  • 15
  • 92
  • 104
5

array[++index] - increment to variable index in current statement itself. array[index++] - increment to variable index after executing current statement.

Dharma
  • 2,965
  • 3
  • 20
  • 36
1

++index will increment index by 1 before it's used. So, if index = 0, then arry[++index] is the same as arry[1].

index++ will increment index by 1 after it's used. So, if index = 0, then arry[index++] is the same as arry[0]. After this, index will be 1.

Steve Chaloner
  • 8,032
  • 1
  • 21
  • 38
1

The different behavior is not specific to arrays.

Both operators increment index by one.

++index returns index+1 while index++ return the original value of index.

Therefore when used to access an array element, the two operators will give different indices.

Eran
  • 374,785
  • 51
  • 663
  • 734
1

let's say index is 0

array[++index] give you element 1 and index is 1 after that

array[index++] give you element 0 and index is 1 after that

Dharma
  • 2,965
  • 3
  • 20
  • 36
Veselin Davidov
  • 6,963
  • 1
  • 14
  • 22
1

The preincrement operator (++index) first increments the variable and only then returns its value. So var = array[++index] is equivalent to:

index += 1;
var = array[index];

The postincrement operator (index++) first returns the value of the variable and only then increments its value. So var = array[index++] is equivalent to:

var = array[index];
index += 1;
Mureinik
  • 277,661
  • 50
  • 283
  • 320