ChiseledAbs ChiseledAbs - 2 months ago 7
C Question

Why this piece of code doesn't change the string?

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

usr usr
Answer

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]