Why this C code (for-loop) is looping forever? -


learning c right , i've made simple for-loop. program check if argument given has 'a' alphabet in it.

int main(int argc, char *argv[]) {     if(argc != 2) {         printf("error: need 1 argument\n");         return 1;     }      int = 0;     char letter;     for(i = 0, letter = argv[1][i]; letter != '\0'; i++) {          switch(letter) {             case 'a':                 printf("%d: 'a'\n", i);                 break;              default:                 printf("%d: '%c' not 'a'\n", i, letter);         }     }      return 0; }                

the result of forever looping program, if change line:

for(i = 0, letter = argv[1][i]; letter != '\0'; i++)

for(i = 0, letter = argv[1][i]; argv[1][i] != '\0'; i++),

the code runs fine. why this?

if ever have trouble debugging loop, helps think of for (initialise; test; increment) equivalent to:

initialise; while (test) {     // code     increment; } 

also should never use comma operator. it's ok use if know doing, if knew doing wouldn't have posted question here.

so in loop for(i = 0, letter = argv[1][i]; letter != '\0'; i++) , replacing comma semicolon can @ as:

i = 0; letter = argv[1][i]; while (letter != '\0') {     // other code (which doesn't modify letter)     i++; } 

and should clear why loop doesn't terminate.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -