1

NOTE: I know I can move the declaration outside the loop.

I want to declare a couple of variables in a for loop:

for ( int x = 0, int y = 0 ; ; )
{
}

,but this doesn't work since I can't specify a type after the comma ,. In this case, removing the second int or declaring y outside the loop would fix the problem, but what if I want to declare both variables inside the loop and also have different types?

Can I have something like:

for ( int x = 0, float y = 0 ; ; )
{
}

?

2

5 Answers 5

8

This is impossible; the C++ grammar just won't admit it. The closest you can get to this is putting an extra scope around the loop:

{
    int x;
    float y;

    for (x=0, y=0;;) {
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

As pointed out in other answers you can do it by declaring a struct type inside the for statement, or using another aggregate type like std::tuple.
@bames53: yes, but strictly, that won't give you more than one variable with scope restricted to the for loop.
5

no, you can only declare variables of one type in there. What you could do is work around this issue with std::pair, std::touple or some similar construct:

for(std::pair<int, float> p = std::make_pair(0, 0.0f);; )
{
    p.first++;
    p.second *= 0.5f;
}

3 Comments

I was also going to mention pair/touple. I would still caution that this seems like a strange use of a for statement. If one of the variables isn't specifically used for constraining the iteration, it shouldn't be mashed into the for.
I agree, although this is a way, its not a way I would normally use. It doesn't help with the readability of the loop body and the construct seems very unusual when glancing through code. I'd go with solution that @larsmans proposes.
You can also declare a struct type with members. See my answer.
2

C++ allows you to do this:

for( struct {int x; float y;} s; s.x<10; s.x++,s.y*=2.0f) {

}

MSVC has a bug such that it does not allow this, but more standards compliant compilers allow it.

Comments

0

No, that's not possible, they all have to be of the same type.

Comments

0

You can't.

My suggestion would be to split the code inside into a separate function to keep it readable:

template<typename O, typename I>
O copy(I in, I end, O out) {
    for(; in != end; ++in, ++out)
        *out = *in;
    return out;
}

IMO, this is much nicer than inventing a new scope or extending the lifetime of iterators, plus it makes you think whether the code can be genericized.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.