ChiseledAbs ChiseledAbs - 1 year ago 64
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
by the next character
. Take a look at the code :

#include <stdio.h>

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 Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download