Yes, you can change the counter in a loop, and sometimes it can be very useful. For example, when parsing command line arguments, where there is an option flag followed by a value. An example of this is shown below:
Enter the following command:
program -f filename -o option -p another_option
the code:
#include <string.h> int main(int argc, char** argv) { char *filename, *option, *another_option; if(argc > 1){ for(int i=1; i<argc; i++){ if(strcmp(argv[i],"-f")==0){ filename = argv[++i]; } else if(strcmp(argv[i],"-o")==0){ option = argv[++i]; } else if(strcmp(argv[i],"-p")==0){ another_option = argv[++i]; } else { printf("Option \"%s\" not recognized, skipping\n",argv[i]); continue; } } } /* end if argc > 1 */ return 0; }
The sample program automatically increments the counter to access the correct command line. Of course, there are ways to enable counters, etc., but in this case they will make the code more cumbersome.
As others have pointed out, this is what many people write errors, and you need to be careful when adding counters to loops, especially when the loop depends on the value of the counter.
Mosby
source share