Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this for loop not correct?

Tags:

c++

for-loop

Visual Studio is telling me that this for loop isn't correct. Error Messages are:

  • type bool unexpected
  • ok is undeclared identifier
  • missing ; before }

infos:

-recordset.Select return a long -MoveNext a bool

for (size_t i = 0, bool ok = recordset.Select(Adress::getSQLStatement() + "Where A05.recid = %ld", i); ok; ok = recordset.MoveNext(), i++) {
    at(i).Save(recordset);
}
like image 843
Lord_Curdin Avatar asked Feb 07 '23 06:02

Lord_Curdin


2 Answers

It's as StenSoft said. But you can define an anonymous structure in the loops first statement, and initialize that.

#include <iostream>
using namespace std;

int main() {
    for (struct {size_t i; bool ok;} s = {0, true}; s.ok; ++s.i) {
        s.ok = s.i < 10;
        cout << s.i;
    }
    return 0;
}

But IMHO, while it works, it's more trouble than it's worth. Better restructure you code.

like image 100
StoryTeller - Unslander Monica Avatar answered Feb 22 '23 01:02

StoryTeller - Unslander Monica


First off, you can of course rewrite your loop like so:

{
    bool ok = recordset.Select(...);
    for (std::size_t i = 0; ok; ok = recordset.MoveNext(), ++i)
    {
        /* ... */
    }
}

But the meta lesson here is that almost all loops are for-loops, and when you think your structure is different, think again. There's probably a rewrite in terms of for-loops that makes your logic clearer. Your present code doesn't distinguish an initial error from a "no more records" error later. With the new code, that's now explicitly possible:

if (bool ok = recordset.select(...)) 
{
    for (std::size_t i = 0; ok; ok = recordset.MoveNext(), ++i) { /* ... */ }
}
else
{
    // handle initial error
}

I would probably even get rid of the redundant ok variable:

if (recordset.select(...)) 
{
    for (std::size_t i = 0; ; ++i)
    {
        /* ... */

        if (!recordset.MoveNext()) break;
    }
}
else
{
    // handle initial error
}
like image 32
Kerrek SB Avatar answered Feb 21 '23 23:02

Kerrek SB