Why does while (str[i] == str[++i]); make an infinite loop?

88 Views Asked by At

I want to let i be the index of the first character different from str[i] (where str is an array of char).

(Let me ignore the out-of-bound condition here.)

What I tried is:

char str[6] = {'h', 'h', 'h', 'a', 'a', '\0'};
int i = 0;
while (str[i] == str[++i]) ;

but this falls into an infinite loop. (i adds up to some big numbers.)

Same happened with while (str[i++] == str[i]) ;.

I know I can successfully do this by:

while (str[i] == str[i+1]) i++;
i++;

but I don't understand why the first two codes I tried don't work.

Why does while (str[i] == str[++i]); lead to an infinite loop?

1

There are 1 best solutions below

5
Carlotta Fabian On

I'm pretty sure (str[i++] == str[i]) does the following:

  1. evaluating str[i] == str[i]
  2. i++ to be sure consider using a debugger to step through the code

and the other one just does it in the opposite order