Is there a difference in decrement operatos in D? -


i'm using dynamic array implement stack. wrote pop following:

int pop() {         int n = arr[--arr.length];         return n; } 

using above code range violation error @ run-time. using following code:

int pop() {         int n = arr[arr.length - 1];         arr.length--;         return n; } 

it works fine. don't understand why, me both should equivalent. missing?

edit: maybe why --arr.length cause element i'm going access "removed" array?

also, push(n) arr ~= n;

you're removing element before grab it. have retrieve element, , reduce size of array.

--arr.length reducing length of array, , returning new reduced size. attempt int n = arr[arr.length].

here's simple work-through of int n = arr[ --arr.length ] 1 element:

  • arr.length = 1
  • last element @ position 0
  • evaluate --arr.length
    • arr reduced 0 elements
    • arr.length returns 0
  • evaluate int n = arr[0].
    • arr empty, breaks.

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -