I wrote some code that copies one char array to another array.
void copy(char dest[], char src[])
{
int index = 0;
while ((dest[index++] = src[index]) != '\0') { }
}
I thought the assignment operator evaluates values from right to left. So src[index] will be assigned to dest[index] first, where index is 0. And index will be increased by 1.
I expected the whole array is copied to another array, and the code was worked.
But, when I wrote that code in main funciton without wrapper funciton like before, it doesn't work anymore; It dosen't copy the first letter of the array src.
So I assume that the assignment operator first evaluate unary opterator and handle the assign part and re-write the code.
int main()
{
char src[] = "Hello, world!";
char dest[100];
int index = -1;
while ((dest[++index] = src[index]) != '\0') { }
printf("%s\n%s", src, dest);
}
If the initial index is -1, it works. I guess I assumed right.
My question is: How does it work in some function like copy above, but doesn't work in main function? And how the assignment operator handles unary operators like above?
Or is it just Undefined Behavior in C?
P.S. I tried the very same code on java and it doesn't work properly in both main and its own function like copy above.