1

Sample code here:

static class stack 
{
    int top=-1;
    char items[] = new char[100];

    void push(char x) 
    {
        if (top == 99)
            System.out.println("Stack full");
        else
            items[++top] = x;
    }
}

What exactly happens when items[++top] occurs?

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
Maciaz
  • 1,084
  • 1
  • 16
  • 31
  • What part of the code is not clear? Is it the `items[...]` syntax or the `++top` syntax? Or both? – Daniel Pryden Jan 16 '18 at 13:44
  • Look up `pre-increment` and `post-increment` to explain the `++top`. [Here is a link to Java docs for arrays](https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html) – TheCrzyMan Jan 16 '18 at 13:47
  • [What does x-- or x++ do here?](https://stackoverflow.com/q/4104944) [What is the difference between a += b and a =+ b , also a++ and ++a?](https://stackoverflow.com/q/5098282) [Assignment, Arithmetic, and Unary Operators](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) – Bernhard Barker Jan 16 '18 at 14:00

2 Answers2

6

It's pre incrementation. It's equal to:

void push(char x) 
    {
        if (top == 99)
            System.out.println("Stack full");
        else {
            top = top + 1;
            items[top] = x;
        }

    }
Vel
  • 524
  • 3
  • 11
2

This called Pre-increment, so this items[++top] = x; equivalent to :

top++; // this also equivalent to top+=1; or top = top + 1;
items[top] = x;
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140