Search code examples
javareturnpostfix-operator

Java: Other possible forms for return statement


Suppose I wish to return tos = tos-2, than how can the code be modified?

int pop() {
    System.out.print("tos   = " +tos+"  ");
    if (tos<0) {
        System.out.println("Stack limit reached .. UNDERFLOW");
        return 0;}
    else {
        return stck[tos--]; 
    }
}

Solution

  • Java doesn't have an unary "decrement by two" operator, so you'll have to split it to two lines:

    tos -= 2;
    return stck[tos + 2];
    

    Or use a temp value for readability:

    tos -= 2;
    int returnIndex = tos + 2;
    return stck[returnIndex];