Assignment in a WHILE condition

Published 01-17-2005 5:34 PM | jokiz
Before, I used to think that in C, the assignment operator always evaluate to true.  It is because of this context:
[code language="C#"]
while (intLeft == intRight)
    //do whatever

If you mistyped the comparison operator (==) as a single equal sign (=) for assignment (of course it will compile and run since we were using Turbo C), the initial test of the while condition succeeds since I always test the code with intRight’s value as non-zero, and often leads to an infinite loop.

I just found out earlier that the assignment operator always evaluate to the value of the LHS which takes the value of RHS after the assignment.  And since it is used in a while condition, the integer value is treated as boolean (zero or non-zero), talk about strong type system of .NET.
Filed under: , , ,