Just wondering if the condition of an if
statement can be a for
loop in C++14. For example:
using namespace std;
if (for (int i = 0; i < 10; i++)){
cout << "The number now is " << i << endl;
}
Just wondering if the condition of an if
statement can be a for
loop in C++14. For example:
using namespace std;
if (for (int i = 0; i < 10; i++)){
cout << "The number now is " << i << endl;
}
A condition has to be something which can be evaluated as a boolean (such as a boolean literal, a function call which returns a boolean, you name it), or something convertible to a boolean e.g. via a bool()
type conversion operator. A for
loop is not evaluated as anything. It is simply a block of code which runs under certain conditions in a certain manner.
So no, you can't treat a for
loop as if it is a boolean expression. It isn't an expression.
If you wanted to, you could create a function which runs a for loop and then returns a boolean. You could then use the output of that function call as a condition (e.g. if (my_function()) {...}
).