Bo Persson wrote:
I believe it really *is* a difference in culture. For those of us that have used C++ for a long time, without a heavy C background, it is just as confusing as it is for Bob - but in the opposite direction.
If you are used to almost always have the loop counter (or iterator!) declared inside the for statement, it is equally confusing when it is not. There are several other little differences as well, between
for (i=0; i<x ;i++)
and
for (int i=0; i != x; ++i)
C and C++ really *are* two different languages. If you try to read Crafty as C++, it is a bit hard to read, because it is written in C.
I think C versus C++ is not the issue here, but whether this C++ feature is dubios or not.
Is this correct?
Code: Select all
void foo() {
for (int sq=0; sq < 64; sq++) {...}
for (int sq=0; sq < 64; sq++) {...}
}
Or this?
Code: Select all
void foo() {
for (int sq=0; sq < 64; sq++) {...}
for (sq=0; sq < 64; sq++) {...}
}
It may depend on the c++ compiler. In such cases - like Bob - I prefere the C style if I use multiple loops with the same iterator. To keep the iterator pattern consistant, it is fine to use it don't matter how many loops with same iterator occur.
Code: Select all
void foo() {
int sq;
for (sq=0; sq < 64; sq++) {...}
for (sq=0; sq < 64; sq++) {...}
}
I pragmatically like the convenient on the fly declaration in small routines with one simple loop. But as Bob mentioned, one should be aware of the "undefined" or compiler dependent scope outside the loop.
Code: Select all
// return: 0..63 if square found, otherwise 64
int firstSquareOfPiece(int* board, int piece) {
for (int sq=0; sq < 64; sq++)
if ( board[sq] == piece ) break;
return sq; // hmmm
}
int firstSquareOfPiece(int* board, int piece) {
for (int sq=0; sq < 64; sq++)
if ( board[sq] == piece ) return sq;
return 64;
}
int firstSquareOfPiece(int* board, int piece) {
int sq = 0;
for (;sq < 64; sq++)
if ( board[sq] == piece ) break;
return sq;
}