Add warning about modifying an index in a for loop. Without this warning the kind of errors introduced in code are likely to be very difficult to debug (core dump). Example code to reproduce below. Current commandline used to compile: -ansi -pedantic -Wall -O. #include <iostream> using namespace std; int main(int argc, char** argv) { int loopndx; int indexes[10]; for( loopndx=0 ; loopndx <=10 ; loopndx++) { if (loopndx==5) { loopndx=666666; } cout << indexes[loopndx]; } return (EXIT_SUCCESS); }
You mean like g++ -S -O2 t.C -Wall t.C: In function ‘int main(int, char**)’: t.C:12: warning: array subscript is above array bounds ? Seriously, there is too many code around modifying the induction variable in a valid way.
(In reply to comment #0) > Add warning about modifying an index in a for loop. > > Without this warning the kind of errors introduced in code are likely to be > very difficult to debug (core dump). > > Example code to reproduce below. Current commandline used to compile: -ansi > -pedantic -Wall -O. > > #include <iostream> > using namespace std; > > int main(int argc, char** argv) { > int loopndx; > int indexes[10]; > > for( loopndx=0 ; loopndx <=10 ; loopndx++) { > if (loopndx==5) { > loopndx=666666; > } > cout << indexes[loopndx]; > } > return (EXIT_SUCCESS); > } >
With my version of g++ I didn't get your example warning about subscript. This would be great. In response to your objection... If any line of code modified the index of a for loop then why use a for loop? It would make more sense to use a while loop. In structured system design, modifying the index of a for loop is "tight" data coupling and lacks logical cohesion. Doing this is on par of a "goto". Mathematically a for loop implies a series or sequence; interrupting that by modifying an index violates the semantic of a series. From a marketing point of view, if you want new adopters, easier to use software that gets the job done can never be wrong if you want broad appeal. The counter is that we want to "haze" developers using the product, making them stronger, limiting the talent pool, thereby creating Conan programmers :) Anyone doing this should at least be warned at a verbose warning level. If they want to modify the index, they are better off with a while loop. Really this philosophical viewpoint may need elevation to a product level (what about a --novice --student --worker --expert --elite warning levels?) (In reply to comment #1) > You mean like > > g++ -S -O2 t.C -Wall > t.C: In function ‘int main(int, char**)’: > t.C:12: warning: array subscript is above array bounds > > ? Seriously, there is too many code around modifying the induction variable > in a valid way. >
Fixed in 4.3.0 and above which emits at -O2 -Wall -W: t.cc: In function 'int main(int, char**)': t.cc:12: warning: array subscript is above array bounds