0

I'm looking at string manipulation in C and I don't understand why the statement s1[i] = s1[++i]; won't replace the first H by the next character e. Take a look at the code :

#include <stdio.h>

main()
{
  char s1[] = "Hello world !";
  for(int i = 0; s1[i] != '\0'; ++i)
    s1[i] = s1[++i];
  printf("%s", s1);
}

It prints Hello world ! instead of el r

ChiseledAbs
  • 1,963
  • 6
  • 19
  • 33

2 Answers2

4

Your program has undefined behaviour because in this statement

s1[i] = s1[++i];

i is modified twice between sequence points (The assignment operator = doesn't introduce a sequence point).

gcc (gcc -Wall -Wextra) warns with:

warning: operation on ‘i’ may be undefined [-Wsequence-point]

similarly clang warns:

warning: unsequenced modification and access to 'i' [-Wunsequenced]
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
P.P
  • 117,907
  • 20
  • 175
  • 238
2
undef.c: In function ‘main’:
undef.c:7:24: warning: operation on ‘i’ may be undefined [-Wsequence-point]
             s1[i] = s1[++i];
                        ^~~

Enable your compiler warnings and pay attention to them. The compiler is your friend.

What this warning means:

There is no rule in C saying which side of the assignment should be evaluated first. In this case, it seems that the right side happened to be evaluated first but in general the result will be undefined.

jforberg
  • 6,537
  • 3
  • 29
  • 47
  • I don't have warning message with `cc` that's strange. – ChiseledAbs Oct 07 '16 at 15:14
  • @ChiseledAbs Which compiler are you using? Ensure you are running with the -Wall flag, or equivalent for your compiler (refer to the manual of your particular compiler). Programming without warnings is dangerous and unnecessary. – jforberg Oct 07 '16 at 15:15