-2

In the code below, when I put the ++ operator after the 'tos' I recieve an error. But if i place it before 'tos' the code runs. Why is this so?

void push(int item){
if(tos==9)
    System.out.println("The stack is full");
else
    stck[++tos]=item;
}

3 Answers3

4
  • ++tos means increments tos and then returns the expression value.
  • tos++ means returns the expression value then increments tos.
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
2

a++ will return a and increment it, ++a will increment a and return it.

http://www.sanity-free.com/145/preincrement_vs_postincrement_operators.html

hegu_141
  • 99
  • 9
1

Both tos++ and ++tos increment the variable they are applied to. The result returned by tos++ is the value of the variable before incrementing, whereas the result returned by ++tos is the value of the variable after the increment is applied.

example:

public class IncrementTest{
public static void main(String[] args){

System.out.println("***Post increment test***");
int n = 10;
System.out.println(n);      // output  10
System.out.println(n++);    // output  10
System.out.println(n);      // output  11

System.out.println("***Pre increment test***");
int m = 10;
System.out.println(m);      // output  10
System.out.println(++m);    // output  11
System.out.println(m);      // output  11
}
}

For more info, read this: http://www.javawithus.com/tutorial/increment-and-decrement-operators Or google post increment and pre increment in java.

Faraz
  • 6,025
  • 5
  • 31
  • 88