-5

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;
}
Sunny267
  • 27
  • 6
  • 3
    Have you tried compiling the code to see if it works? Also, what would you like the effect of this syntax to be? Depending on what you want to happen, there are usually ways of achieving that effect. – cigien Jan 17 '21 at 02:59
  • @cigien I did, it gives two error (I'm using clion), one for the for loop regarding the "expected expression" and one for the i variable on the last line of code, regarding the "use of undeclared identifier 'i' ". – Sunny267 Jan 17 '21 at 03:05
  • No. A `for` statement is not an expression. An `if` statement tests the value produced by an expression. – Peter Jan 17 '21 at 03:07
  • 1
    Well, does that answer your question, then? i.e. it's not possible. – cigien Jan 17 '21 at 03:07
  • 1
    What do you hope to accomplish with that syntax? (How can a loop be a condition?) What's your expected behavior? (When would the loop be "true"?) It might be that your goal is possible even though the syntax you tried does not compile. – JaMiT Jan 17 '21 at 03:11
  • @JaMiT It's just a wonder, haven't yet think of the application. – Sunny267 Jan 17 '21 at 03:23
  • 1
    @Sunny267 I'm not asking for application so much as meaning. What would such a construct mean? Putting together elements to form nonsense, then asking if it is legal is not productive. (However, if you had some inkling of how `if ( for (...) )` might be interpreted as sensible, then your question could be productive.) – JaMiT Jan 17 '21 at 03:26
  • @JaMiT Not an `if/for` but python has a `for/else` construct [for example](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops). – dxiv Jan 17 '21 at 03:40

1 Answers1

2

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()) {...}).

Alexander Guyer
  • 2,063
  • 1
  • 14
  • 20