Liste des Groupes | Revenir à cl c |
bart <bc@freeuk.com> wrote:You have to analyse it first. The kind of loop this expresses is:>Apparently you do not get why sqlite3.c version is better.
I don't know why people think that cramming as much code as possible
into for(...) is a good style of coding. Either into one over-long line,
or spilling over multiple lines; both should fail a code review.
>
Actually here's a example from sqlite3.c:
>
for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
}
>
And this is how you might be forced to write it instead:
>
p=sqliteHashFirst(&pSchema->trigHash);
while (p) {
sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
p=sqliteHashNext(p);
}
>
Yes, it's spread over two more lines, but so what? It's much clearer:
the initialisation is done once and then it's out of the way. Setting p
to the next value is now physically written after the body.
In short, this is separation of concerns. The 'for' construct
is responsible for iteration. Body of 'for' loop is responsible
for computation. You may replace body by empty instruction,
so there are no computation but the loop still correctly goes
over the same sequence. Or you may add instructions to perform
more computation. 'while' version mixes computation with
stepping to the next element. Since in 'for' version all parts
dealing with iteration are together it is easy to check that
they are correct. With 'while' version probablity of forgeting
to step to next element is higher.
FYI: I do not remember making error in a simple 'for' loop.
I do remember cases when I had to use 'while' for iteration
(in non-C languages) and stepping was wrong/missing. So
for me simple loops (your 98% of cases) are not an issue.
The issue are remaining cases, and for them C 'for' worksThat's bizarre. It is exactly like saying you don't have a problem with writing (or forgetting to write) 'break' in 99% of switch-case blocks, because in those 1% of cases where you do want fallthroughit is 'automatic'.
better.
Les messages affichés proviennent d'usenet.