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,988
  • 14
  • 52
  • 97

6 Answers6

6

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,555
  • 31
  • 31
  • 45
Jens
  • 67,715
  • 15
  • 98
  • 113
5

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

Dharma
  • 3,007
  • 3
  • 23
  • 38
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,162
  • 1
  • 22
  • 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
  • 387,369
  • 54
  • 702
  • 768
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
  • 3,007
  • 3
  • 23
  • 38
Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23
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
  • 297,002
  • 52
  • 306
  • 350