Friday, August 12, 2011

Consider the following code. while (x = 3) x = 0;?

The = operator in the condition is causing the value of 3 to be igned to the variable x. The result is that the while condition will evaluate to whatever value was used in the ignment i.e. 3. Since this is a non zero value, it is treated as a logical "true", thus the while statements will always execute. The exhibited behaviour is the variable x perpetually oscillating between the values of 0 and 3. The actual operations carried out within the loop are irrelevant however, since it is exclusively the result of the ignment that governs the result of the while condition.

No comments:

Post a Comment