-1
array[i] = array[--size];

I understand that variable-- is equal to variable - 1 but what is --variable equal to and does it do something special when it is in the array brackets? I guess this removes something from the array I really don't understand the code here.

Tyler
  • 2,346
  • 6
  • 33
  • 59

8 Answers8

3

The code sets size = size - 1 and afterwards copies the element at size to i.

Stephan
  • 7,360
  • 37
  • 46
2

It's simply equivalent to:

size-=1;
array[i] = array[size];
P.P
  • 117,907
  • 20
  • 175
  • 238
2

Your code is identical to:

size--;
array[i] = array[size];

Prefix decrement is very similar to postfix, the only difference being that it evaluates to the result after the decrement, rather than the value before.

obataku
  • 29,212
  • 3
  • 44
  • 57
1

The variable size was defined earlier in your code. The -- infront of the variable name causes to to decrease by 1 prior to executing that line of code. For example if the size variable was set to 5, prior to the assignment occurring the size variable would decrease to 4 and then perform the assignment of array[i] = array[4].

Lipongo
  • 1,221
  • 8
  • 14
1

It's simply does this :

size-=1;
array[i] = array[size];

--variable indicates pre decrement. That is first the value will be decremented and then used.

heretolearn
  • 6,387
  • 4
  • 30
  • 53
1

-- substracts one from the variable, but the position of the -- (or ++) controls when the variable is decremented

  • array[--size] subtracts one before the array is accessed

  • array[size--] would subtract one after the array has been accessed

Marko
  • 20,385
  • 13
  • 48
  • 64
user1642523
  • 371
  • 3
  • 7
0

The array[index] returns the element in the array at the index location.

The --value means evaluate the value as value = value - 1 and then apply the new value in the operation.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
0

i-- and --i do essentially the same thing: They subtract 1 from i. The difference is that i-- will subtract 1 after an action is completed, while --i will subtract one before the action. This makes more sense in the case of a for loop:

for (i = 5; i > 0; i--) {...}

In this case, the for loop will run with i equaling 5, then at the end of the loop, it will repeat, but subtract 1. If the case was this:

for (i = 5; i > 0; --i) {...}

i would have 1 subtracted from it BEFORE the loop runs, so it would start off immediately with 0, but on the other hand, it would also run at the end when i = 0.

Saying --size is like saying the value of size minus 1.

charlieshades
  • 323
  • 1
  • 3
  • 16
  • Do either of them save the new value of the variable though or is it just a temporary thing? – Tyler Sep 03 '12 at 20:22
  • This opening explanation is correct but the for-loop example is incorrect: {...} will run with i = 5 first before being decremented by either '--i' or 'i--', which will amount to the same in this example. – Julian Pinn Nov 18 '19 at 10:15