c++for-loopstatements

Can I have two initializing statements in a "for" loop?


In C++, a for loop normally takes three statements, in the form:

for (init; condition; step)
{
Loop statements
}

Can I place two or more statements in the place of init? Let's say I want to define two starting variables, a and b. To do this, I would use int a = 1; int b = 5;. However, since there is a ; between the statements, C++ would interpret int b = 5 as the condition statement. Is there a way to clump the whole statement into init, perhaps by using brackets? Can something similar be done for step?

Note: I am aware that I can initialize a variable before calling for. However, I feel that it would be more logical to place loop-related statements within the definition of the loop.


Solution

  • No, you can only have one initializing statement. However, frequently you can use the comma operator to achieve the desired result:

    for(int foo = 7, bar = 42; ...; ...) {
        ...
    }
    

    or even

    int foo;
    double bar;
    for(foo = 7, bar = 42; ...; ...) {
        ...
    }
    

    What is not possible, is to declare two variables of different type within the initialization statement:

    //Illegal code!
    for(int foo = 7, double bar = 42; ...; ...) {
        ...
    }