bool condition = i < 5;
This line defines a variable named condition
which has the value true
from this line onwards.
It does not bind the expression from the right side, but only copies the result at the time of assignment.
What you intended is more complicated:
auto condition = [&i](){ return i < 5; };
for ( ; condition() ; )
Now condition
is a function object which can be evaluated repeatedly.
The right hand of the assignment is called a lambda expression, and follows the form [capture scope](parameters){ body with return statement }
.
In the capture scope, you can list variables either by value (without &
) in which case they get copied once when the lambda is declared, or by reference (with leading &
) in which case they don't get copied but the variable inside the lambda is a reference to the variable of the same name outside the lambda. There is also the short form [&]
which captures all variables in the parent scope by reference, and [=]
which captures everything by value.
auto
can be used for brevity in combined declarations + assignments, and automatically resolves the type of the variable from the right hand side.
The closest compatible type you could explicitly specify would be std::function<bool(void)>
(generic container for functions with that signature), the actual type of that object is some internal type representing the naked lambda which you can't write explicitly. So if you can't know the exact type, and you don't want to use a generic container type, auto
is occasionally even necessary.