Assignments often occur in conditions. Because assignment has relatively low precedence, we usually must parenthesize the assignment for the condition to work properly. To see why assignment in a condition is useful, consider the following loop. We want to call a function until it returns a desired value—say, 42:
// a verbose and therefore more error-prone way to write this loop
int i = get_value(); // get the first value
while (i != 42) {
// do something ...
i = get_value(); // get remaining values
}
Here we start by calling get_value
followed by a loop whose condition uses the value returned from that call. The last statement in this loop makes another call to get_value
, and the loop repeats. We can write this code more directly as
int i;
// a better way to write our loop---what the condition does is now clearer
while ((i = get_value()) != 42) {
// do something ...
}
The condition now more clearly expresses our intent: We want to continue until get_value
returns 42
. The condition executes by assigning the result returned by get_value
to i
and then comparing the result of that assignment with 42
.
Without the parentheses, the operands to !=
would be the value returned from get_value
and 42
. The true
or false
result of that test would be assigned to i
—clearly not what we intended!