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;
}
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.
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) {
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With