Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does variable declaration work well as the condition of for loop?

Tags:

What's the return value/type of a declaration like int i = 5?

Why doesn't compile this code:

#include <iostream>

void foo(void) {
    std::cout << "Hello";
}

int main()
{
    int i = 0;
    for(foo(); (int i = 5)==5 ; ++i)std::cout << i; 
}

while this does

#include <iostream>

void foo(void) {
    std::cout << "Hello";
}

int main()
{
    int i = 0;
    for(foo(); int i = 5; ++i)std::cout << i; 
}
like image 439
Felix Crazzolara Avatar asked Oct 12 '16 07:10

Felix Crazzolara


People also ask

Can you declare a variable in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Can you declare a variable in a for loop in C?

In C and C++, there are currently two places you can declare a variable “in a for loop:” in the for statement itself, and in the statement it controls (loops). Consider: for (int i = 0; i < 42; ++i) {

Why is it not a good idea to to modify a for loop variable inside the loop body?

for loops should be reserved for simple iteration, use while loops for more complicated cases. Most developers assume that the for loop iteration statement is the only thing that changes the value of the loop counter, so changing it inside the loop body can lead to confusion.


1 Answers

The for loop requires condition to be either an expression or a declaration:

condition - either

  • an expression which is contextually convertible to bool. This expression is evaluated before each iteration, and if it yields false, the loop is exited.
  • a declaration of a single variable with a brace-or-equals initializer. the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.

The 1st code doesn't work because (int i = 5)==5 is not a valid expression at all. (It's not a declaration either.) The operand of operator== is supposed to be an expression too, but int i = 5 is a declaration, not an expression.

The 2nd code works because int i = 5 matches the 2nd valid case for condition; a declaration of a single variable with a equals initializer. The value of i will be converted to bool for judgement; which is always 5, then leads to an infinite loop.

like image 150
songyuanyao Avatar answered Sep 29 '22 16:09

songyuanyao