1

I am trying to achieve a "wrap around" effect in a circular array. When I push an item to front, I want it to be stored in decreasing locations. When I push to front, I'm trying something like this:

items[front] = ch;
front = (front - 1) % capacity; 

But this does not wrap around like I would expect. Front starts out at 0, and when the second line executes, front becomes -1. Shouldn't front become 6 after the second line executes? My data structures textbook seems to think so.

Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
chillpenguin
  • 2,989
  • 2
  • 15
  • 18

1 Answers1

3

That is how % works in c++. To get the effect you want try this:

front = (front + capacity - 1) % capacity; 
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
The Dark
  • 8,453
  • 1
  • 16
  • 19
  • 1
    `front = (front > 0 ? front : capacity) - 1;` sounds better to me. Also, if `front` is an `unsigned` type then OP's operation should be correct too. – Chnossos May 04 '14 at 01:15