Question

I recently looked up what is the difference between ++i and i++ and found that apparently it doesn't matter in for loops but it does in this case:

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4

Does it work the same for --i and i--? I am wondering because I have come across the following exercise:

// pops the first non-null element in a stack
public E popFirstNonNull() throws EmptyStackException {

while ( (top >= 0) && ( S[top] == null ) ) {
    top--;
}
if ( top >= 0 ) {
    E topNonNull = S[top];
    S[top--] = null; //for garbage collection
    return topNonNull;
}
else {
    throw new EmptyStackException();
}

}

If ++i / i++ and --i / i-- behave the same shouldn't this line: S[top--]=null; be changed to: S[--top]=null

Was it helpful?

Solution

No.

What the code does is

  • remember the top element in topNonNull
  • null out the top element and then
  • decrease the top-"pointer" in the S[top--]=null line
  • return topNonNull

If you change this to S[--top]=null then you will null out a different element, which is not what you want.

OTHER TIPS

++i / i++ and --i / i-- behave the same way. You are right impact of both (top-- and --top)are different in your case

 S[top--] = null; //null will be assigned to current index() and than it will decrease top.  

and

S[--top] = null; // it will decrease top and null will be assigned to decreased top.

Yes, they behave the same.

Regarding the example: no, it should not be changed. The meaning of

S[top--] = null

is to replace the value that was just read with null. So:

E topNonNull = S[top];
S[top--] = null; //for garbage collection

first reads s[top] and assigns it to topNonNull, then replace the value just read with null, so top must stay the same and THEN it can be decreased to point at the next non-null value.

Yes, --i means i = i - 1 BEFORE the compute and i-- AFTER the compute. So it is analog to ++i and i++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top