A conditional statement that I can't understand

Viewed 73

I saw a few lines of code in a C++ tutorial video

void copy_string(char* from, char* to)
{
    while ((*to = *from) != '\0')
    {
        to++;
        from++;
    }
}

The function is used to copy the string "from" into the string "to", but I can't understand the conditional statement inside the while loop. Why is it able to assign and compare at the same time?

2 Answers

It's both an assignment *to = *from as well as a comparison

(*to = *from) != 0

It first assigns the dereferenced pointer from "from" to "to" then checks if the assigned value was equal to 0 which is a null terminator. If so, then exit the loop and the copying is done.

Why is it able to assign and compare at the same time?

The same expression both assigns and compares because it contains a separate operator for each purpose.

= is an assignment operator. It assigns the value of the right-hand operand to the left-hand operand (this is technically a side effect) and it evaluates to the value that was assigned. That it evaluates to a value may be the point you are missing.

!= is a comparison operator. It determines whether the values of its left-hand and right-hand operands are unequal. If so, it evaluates to 1, otherwise, it evaluates to 0.

There is also ==, a comparison operator that evaluates whether the values of its left-hand and right-hand operands are equal (opposite of !=) without modifying the value of either one.

Do note, however, that although the overall expression performs both assignment and comparison, those don't necessarily happen at the same time.

Related