Reputation: 11439
Here I have a simple algorithm that computes the square of a number by adding up all of the odd numbers equal to the inputted number, such that:
1 = 1 = 1-squared
1 + 3 = 4 = 2-squared
1 + 3 + 5 = 9 = 3-squared
and so forth. The algorithm is as follows:
int triangleSquare(int number) {
int product = 0;
int currentOdd = 1;
while (number--) {
product += currentOdd;
currentOdd += 2;
}
return product;
}
My question is about the segment:
while (number--) { ... }
For some reason I get different results between while (--number)
and while (number--)
, which I assume is because --number
should decrement first before performing the while loop (and vice-versa for number--
). My question is, why does it make a difference? Shouldn't the while loop always execute last, regardless of the increment order? I must be missing something obvious, but that seems very odd to me, almost as though number--
makes the conditional behave like a do {...} while()
loop.
Upvotes: 1
Views: 2517
Reputation: 4813
while (number--)
does the following:
while (number)
number--
On the other hand while (--number)
does this:
--number
while (number)
with the new valueAnd that's the difference.
Upvotes: 2
Reputation: 153929
This is a horrible way to write code, but...
An expression has two characteristics: a return value, and side
effects. The decrementation is the side effect; it is the same
for --number
and number--
. The condition in the while
,
however, depends on the return value; --number
returns the
value after the decrementation; number--
the value before
the decrementation. When the decrementation actually takes
place on the variable is not really specified (for either): some
time after the preceding sequence point and before the following
one.
In other words: --number
is the equivalent of:
int
decr( int& number )
{
number -= 1;
int results = number;
return results;
}
and number--
is the equivalent of:
int
decr( int& number )
{
int results = number;
number -= 1;
return return;
}
In both cases, you're testing the return value of the function.
Upvotes: 1
Reputation: 754130
The two candidate loops could be written (are equivalent to):
while (number-- != 0)
while (--number != 0)
Consider what happens when number == 1
at loop entry:
number
is compared to zero and then decremented; since 1
is not 0
, the loop body is executed.number
is decremented and then compared to zero; since 0
is 0
, the loop body is not executed.That's the difference!
Upvotes: 3