If I have code like:
int pop()
{
return stack[--stp];
}
I know that it is doing two things. It is returning the value contained in the one-dimensional array ‘stack’ in element ‘stp’. It is also decrementing ‘stp’.
But which order does this happen in?
Does it return the value of element stp, then decrement stp?
Or does it decrement stp, then return the value of the element now referred to by the decremented stp?
If the code is:
int top()
{
return stack[stp-1];
}
Does it work any differently?
My apologies, I know this is very common coding style – I still have some trouble making sense of concise, uncommented code – even basics like this. Sorry.
It will decrement
stp, and then return the value from the array at the location of the newstpvalue.--stpis a “prefix decrement”, and it is defined to decrement the argument (stp), and then return the new value. It has a counterpart called the “postfix decrement”,stp--, which decrementsstpand then returns the old value – sostack[stp--]will give you the value the currentstpoffset, but still decrementstp.Finally, your version with
stack[stp-1]will return the value from the same place asstack[--stp], butstpitself will be unchanged.