Can someone please explain this code.

So heres the code. It first creates and array of items

typedef unsingned long Item ; 

int main(){
  Item items[4];
  return 0;

Now lets say that user has input some values into the array by some input method .
(BTW the purpose of items is to act like a stack from where stuff can be popped or pushed into)

now there's this function that can pop stuff out of the Items array
i is 4 since the array is completely filled , everytime the program uses the pop function the last value is removed from the array, how does this work ?
bool pop(Item & item , int i){
   item = items[--i];
This piece of code doesn't really make sense to me.

What the pop function does is decreasing the i variable , since the -- precedes the variable, before it picks the Item of index i-1 out of the array and copies it into the address given by the Item& item variable. The reason why the function decreases the i probably is that you can access the first array element by passing i = 1 rather than i = 0. Since there is no global variable which holds the amount of valid items in the array it is up to the programmer to know at which array position to pop or push.

I hope I helped you a bit.

Last edited on
Topic archived. No new replies allowed.