Reputation: 2061
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
Upvotes: 0
Views: 120
Reputation: 121397
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]
Upvotes: 4
Reputation: 6752
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.
Upvotes: 2