Why does adding a semicolon after 'for (…)' change the meaning of my program so dramatically?

前端 未结 6 2182
猫巷女王i
猫巷女王i 2020-12-04 04:30

I wrote the following class:

  public class TestOne {
     public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100         


        
6条回答
  •  青春惊慌失措
    2020-12-04 04:41

    This is not a bug. The semicolon becomes the only "statement" in the body of your for loop.

    Write this another way to make it easier to see:

    for (int i = 0; i < 100; i++)
        ;
    
    {
        count++;
    }
    

    The block with count++ becomes a bare block with a single statement, which isn't associated with the for loop at all, because of the semicolon. So this block, and the count++ within it, is only executed once.

    This is syntactically valid java. for (int i = 0; i < 100; i++); is equivalent to:

    for (int i = 0; i < 100; i++)
    { ; } // no statement in the body of the loop.
    

    for loops of this form can be useful because of the side-effects within the loop increment statement or termination condition. For instance, if you wanted to write your own indexOfSpace to find the first index of a space character in a String:

    int idx;
    
    // for loop with no body, just incrementing idx:
    for (idx = 0; string.charAt(idx) != ' '; idx++);
    
    // now idx will point to the index of the ' '
    

提交回复
热议问题