0

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
  • 57,282
  • 15
  • 95
  • 133
Maciaz
  • 978
  • 1
  • 13
  • 27
  • 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

5

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
  • 514
  • 4
  • 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;
YCF_L
  • 51,266
  • 13
  • 85
  • 129