0

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.

S.Y. Kim
  • 73
  • 6
  • 3
    The code has undefined behavior. – Vlad from Moscow Dec 26 '21 at 08:05
  • (Comparing with Java's evaluation isn't going to help. Java has much more strictly defined semantics for evaluation of expressions. At best it will mislead you.) – Mat Dec 26 '21 at 08:09
  • 1
    UB: the function should be `while ((dest[index] = src[index]) != '\0') { index++; }` – Weather Vane Dec 26 '21 at 08:18
  • 1
    *"How does it work in some function"*. Undefined behavior means "no rules". So it doesn't have to be consistent, or anything. – BoP Dec 26 '21 at 10:25

0 Answers0