pete said:
Michael said:
pete schrieb:
Vladimir S. Oka wrote:
Eric Sosman opined:
CBFalconer wrote:
pete wrote:
... snip ...
As long as (*p) is defined and (*q) is defined,
there is nothing wrong with (*p++ = *q++).
Assuming p != q.
Even if p == q. (Confession: I very nearly made
the same mistake.)
Now I can see it as well! Apologies for the confusion.
Now that I actually thought it through, isn't the above the very
construct K&R use to implement `strcpy()`? I left my copy at work, so
I can't look it up, but I'm pretty sure. Along the lines of:
while (*p++ = *q++)
;
Yes.
/* strcpy: copy t to s; pointer version 3 */
void strcpy(char *s, char *t)
{
while (*s++ = *t++)
;
}
You can see how that implementation of strcpy
would be undefined with something like:
char char_array[] = "xx\0";
strcpy(char_array, char_array + 1);
though
memmove(char_array, char_array + 1, 1 + strlen(char_array + 1));
would be fine.
Why? How? I cannot see anything undefined in that.
If you wrote "strcpy(char_array + 1, char_array);", then I would
agree.
That's what I meant write.
I must be going mad, or missing something here - are you saying that
the code below gives UB?
#include <stdio.h>
void strcpy(char *s, char *t)
{
while(*s++ = *t++)
;
}
int main(void)
{
char char_array[] = "xx\0";
strcpy(1 + char_array, char_array);
return 0;
}
If 'yes', can you explain why please.
while(*s++ = *t++)
As far as I can see, the assignment expression here will 'run' like
this:
1. eval *t
2. take value found in '1' - write to *s
3. increment s then t, OR, increment t then s.
4. repeat.