1

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?

Seoyeon Oh
  • 11
  • 2
  • 10
    This causes undefined behavior, because there's no sequence point between the two sides of the `==`. – Barmar Jan 03 '23 at 17:13
  • And you get an infinite loop if it's compiled as `while (++i, str[i] == str[i])` – Barmar Jan 03 '23 at 17:15
  • 3
    You're basically assuming that expressions are evaluated left-to-right. That's true in some languages that adopted C syntax (e.g. JavaScript and PHP), but not C itself. – Barmar Jan 03 '23 at 17:17

1 Answers1

-3

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

  • The OP's code uses pre-increment, not post-increment. – Barmar Jan 03 '23 at 17:16
  • 1
    @Barmar OP tried both. – Konrad Rudolph Jan 03 '23 at 17:16
  • 1
    *the other one just does it in the opposite order* There is no "order" to the operations as there is no sequence point in the code. Reading and modifying the same variable without an intervening sequence point invokes undefined behavior. – Andrew Henle Jan 03 '23 at 17:24
  • 1
    The language doesn't say exactly when the updated value of `i` is stored back, just that it happens *sometimes* before the `;`. Reading it again before it is updated is an error. – BoP Jan 03 '23 at 17:31
  • 1
    @Eric - Yes, but I was talking about the example `while (str[i++] == str[i]) ;` – BoP Jan 03 '23 at 18:31