7

I am trying to understand this code in Java 7 environment,

int T = getIntVal();
while (T--> 0) {
 // do stuff here
}

T is not modified within the while loop. Can someone explain this code?

Vel
  • 767
  • 5
  • 10
  • 24
  • 2
    [Here's a related question](http://stackoverflow.com/questions/1642028/what-is-the-name-of-the-operator-in-c) which should give you the answer (even though it's c++, the behavior is the same). – resueman Aug 25 '16 at 17:02
  • 1
    What do you think `T--` does? – bradimus Aug 25 '16 at 17:03
  • 2
    it is a bad practice to use a variable name that starts with block letters. There is no such expression --> in java. dont confuse betweenn -- and > . – PKR Aug 25 '16 at 17:08

2 Answers2

19

what confuses you is that there is no whitespace between the T-- and the >, so you might think there's a --> operator.
looking like this:

while (T-- > 0) {

}

It makes more sense, in every loop you decrease T by one

Nir Levy
  • 12,750
  • 3
  • 21
  • 38
2

The -- (decrement) operator will subtract from T each time the loop is run (after the loop condition is run since it as after T).

The simplest way is to just try it out:

public class Tester {

   public static void main(String[] args) {
      System.out.println("-------STARTING TESTER-------");
      int T = 5;
      while (T-- > 0) {
         System.out.println(T);
      }
      System.out.println("-------ENDING TESTER-------");
   }

}

Output:

-------STARTING TESTER-------
4
3
2
1
0
-------ENDING TESTER-------

If the -- operator was before T, the output would look like this (since it subtracts before the loop condition is run):

-------STARTING TESTER-------
4
3
2
1
-------ENDING TESTER-------
Adam
  • 2,214
  • 1
  • 15
  • 26