Java: other possible forms for the return statement

Suppose I want to return tos = tos-2

, how can I change the code?

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

      

+3


source to share


5 answers


Java does not have a unary decrement by two operator, so you have to split it over two lines:

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

      



Or use a temp for reading:

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

      

+1


source


If you want to revert the position of the array before the change tos

(similar to how you did it return stck[tos--]

):

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

      



Otherwise,

tos-=2;
return stck[tos];

      

+1


source


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

      

0


source


int pop(){

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

      

0


source


stop using postfix .: D

int pop() {
        int tos = 2;//3

        System.out.print("tos   = " + tos + "  ");
        if (tos < 0) {
            System.out.println("Stack limit reached .. UNDERFLOW");
            return 0;
        } 

        return stck[tos-=2];
    }

      

0


source







All Articles