tonni
tonni

Reputation: 1255

Struct in for loop c++

I wonder is it possible to put struct in for loop instead of just one variable, i read from this answer, but can't get think work, here is code:

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}

Errors are:

    error C2332: 'struct' : missing tag name
    error C2228: left of '.b' must have class/struct/union
    ...

How to make code work on c++ 11, visual studio 2012?

Upvotes: 2

Views: 405

Answers (3)

Danvil
Danvil

Reputation: 23031

You can use an std::tuple (reference):

#include <tuple>

for(std::tuple<int,char> s(0,'a'); std::get<0>(s) < 5 ; ++std::get<0>(s)) 
{
    std::cout << std::get<0>(s) << " " << std::get<1>(s) << std::endl;
}

Not sure how well this is support by MSVC2012. Update: it does work with MSVC2012.

Upvotes: 3

txtechhelp
txtechhelp

Reputation: 6777

As comments have pointed out, with what you are trying to do, some compilers might not exactly give the results you are wanting.

If you're merely trying to limit the scope of a struct or variable type to a limited area (without having to go into another function, etc.), you can just add some extra brackets around your code, ex:

{ // scope start
struct X { int a; char b; };
for(X s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}
} // scope end .. struct X no longer 'visible'

This has the advantage of being more 'readable' as well as have a better chance of 'playing nice' with other compilers.

Hope that helps

Edit:

Even the above code doesn't play well with VS2012, here's what DID work with VS2012 limiting scope:

{ // scope start
struct X { int a; char b; X(int z, char y) : a(z), b(y) {} };
for(X s(0, 'a') ; s.a < 5 ; ++s.a)
{
    std::cout << s.a << " " << s.b << std::endl;
}
} // scope end .. struct X no longer 'visible'

Upvotes: 2

TobiMcNamobi
TobiMcNamobi

Reputation: 4813

My suggestions:

struct X
{
    X(int a_, char b_)
        : a(a_), b(b_)
    {}
    int a; char b;
};

for(X s(0, 'a'); s.a < 5 ; ++s.a)
{
    std::cout << s.a << " " << s.b << std::endl;
}

You have two problems (in VS 2012, that is!): 1. Declaring a struct in the first for statement. 2. Initializing the local variable c with the brace syntax

I get errors for each of these issues separately. But both are addressed with the above code. I hope this comes close enought to what you are searching for.

Upvotes: 2

Related Questions