Re: Fixed for loop
On Friday, 28 June 2013 16:57:42 UTC+3, Gon Solo wrote:
Is there a better way in C++ to make a very simple for loop look
very simple?
#define FOR(i, x) for(int i = 0; i < x; ++i)
FOR(i,3) {
// ...
}
Depends what you mean what is "simple". What you do in that '// ...'
part? For example you seem to assume that most of your "simple" for
loops loop from 0, use int and advance in increments of 1.
If you would also assume that "simple" loop variable is named always
'i' then you can go "very simple" just like that:
#define FOR(x) for(int i = 0; i < (x); ++i)
Lets try to use it.
int main()
{
std::vector<int> vec;
vec.push_back( 1 );
vec.push_back( 2 );
FOR(vec.size())
{
++vec[i];
}
}
MSVC issues a warning that I am comparing signed and unsigned values
somewhere in that macro. That complicates it for me and complications
are not "better". It is generally considered that preprocessor macros
that replace code make it cryptic and may add hard to debug
complications.
I prefer to use C++ that we have:
int main()
{
std::vector<int> vec;
vec.push_back( 41 );
vec.push_back( 42 );
// increment all elements of vec
for (int& n : vec )
{
++n;
}
// output all elements of vec
for (int n : vec )
{
std::cout << n << std::endl;
}
}
Latest versions of clang, gcc and msvc seem to support that syntax.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]