What does it mean when the first “for” parameter is blank?

后端 未结 8 1052
猫巷女王i
猫巷女王i 2020-12-20 19:27

I have been looking through some code and I have seen several examples where the first element of a for cycle is omitted.

An example:

for ( ; hole*2          


        
相关标签:
8条回答
  • 2020-12-20 19:29

    That means loop control variable is initialized before the for loop .

    For C  code,
    
    int i=0;
    for( ; i <10 ; i++) { } //since it does not allow variable declaration in loop 
    
    For C++  code,
    
    for(int i=0 ; i <10 ; i++) { }  
    
    0 讨论(0)
  • 2020-12-20 19:31

    It means that the initial value of hole was set before we got to the loop

    0 讨论(0)
  • 2020-12-20 19:31

    You could omit any of the parameters of a for loop. ie: for(;;) {} is about the same as while(true) {}

    0 讨论(0)
  • 2020-12-20 19:40

    The for construct is basically ( pre-loop initialisation; loop termination test; end of loop iteration), so this just means there is no initialisation of anything in this for loop.

    You could refactor any for loop thusly:

    pre-loop initialisation
    while (loop termination test) {
    ...
    end of loop iteration
    }
    
    0 讨论(0)
  • 2020-12-20 19:40

    Some people have been getting it wrong so I just wanted to clear it up.

    int i = 0;
    for (; i < 10; i++)
    

    is not the same as

    for (int i = 0; i < 10; i++)
    

    Variables declared inside the for keyword are only valid in that scope.

    To put it simply.

    Valid ("i" was declared outside of the loops scope)

    int i = 0;
    for (; i < 10; i++)
    {
      //Code
    }
    std::cout << i;
    

    InValid ("i" does not exist outside the loop scope)

    for (int i = 0; i < 10; i++)
    {
      //Code
    }
    std::cout << i;
    
    0 讨论(0)
  • 2020-12-20 19:46

    Suppose you wanted to

    for (hole=1 ; hole*2 <= currentSize; hole = child)
    

    But the value of hole just before the for loop was already 1, then you can slip this initilization part of the loop:

    /* value of hole now is 1.*/
    for ( ; hole*2 <= currentSize; hole = child)
    
    0 讨论(0)
提交回复
热议问题