Can I if(for(?

Can I?

I need to do make a loop inside a condition. Can it be done? I don't want to call another function to do it. Any way at all without calling separate function inside the if? I just want to do:

1
2
3
4
5
6
7
8
9
10
11
12
13
if (

    for (int i = 0; i<=10; i++)
      {
              //stuff related to the for loop
       }   )

    
{

//stuff related to the initial if condition

};
Last edited on
You could use a boolean-returning lambda that's called at declaration. I do not think a for-loop is a boolean construct, and can therefore not be used in this circumstance.
So... no?
Can you explain to me what you are trying to do?

if it can loop then loop?
You have two options:
1.
1
2
3
4
5
6
7
8
for (int i = 0; i < 10; i++)
{
    // stuff related to the for loop
}
if (condition_calculated_in_for_loop)
{
    // stuff related to the initial if condition
}


2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool condition()
{
    for (int i = 0; i < 10; i++)
    {
        // stuff related to the for loop
    }
}
//  Now you have some code below: 
int main()
{
    if ( condition() )
    {
        // stuff related to the initial if condition
    }
}


In the second option, you are running the for loop and returning a bool value which is evaluated by the if condition. I think this is what you are thinking of.
I never understand these 'can I....?' questions.
Just code it up and try it dude :)
3. If you want to read it in-line :3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int a(13), b(12), c(9);
if
(
    [&]() -> bool
    {
        for (int i(0); i < 100; ++i)
        {
            if (a * b * c - i > 9)
                continue;
            else
                return false;
        }
        return true;
    }()
)
{
    std::cout << "yes!\n";
}
Thanks stew & Bourgond Aries!
@ Mutexe, tried it, didn't work, thought I was doing something wrong.
Topic archived. No new replies allowed.