Reputation: 115
In the following floor loop, how would sum += n --
be evaluated? I'm very, very confused...
int sum;
for(sum=0;n>0;sum+=n--);
Upvotes: 0
Views: 146
Reputation: 505
A very simple example I would like to demostrate.
Let us consider two variables a=1
and b=4
the statement a=b
will assign the value of b to a,
In the statement a=b++
, first the value of b
is assigned to a
and then the value of b
is incremented.
If the value of a
was 1 and value of b
was 4, then after using a=b++
, the value of a
will become 4 and the value of b
will become 5.
The statement a=b++
can be visualised as
a=b;
then
b=b+1;
Similarly, in your case, you have sum+=n--
which can be broken down as
sum=sum+(n--)
or
sum=sum+n
then
n=n-1
Here again, first the value of sum+n
will be assigned to sum
, then the value of n
will be decremented by 1
Upvotes: 0
Reputation: 12047
For sum += n--
the following operations are performed
n
to sum
n
With sum += --n
n
is decrementedn
is added to sum
n--
is called postdecrement, and --n
is called predecrement
Upvotes: 6
Reputation: 44888
That has to do with post- and predecrement operations. Predecrement operations first decrease the value and then are used in other operations while postdecrement ones first get used in operations (addition in the case) and decrement the value only after this.
All in all, the order will be as follows:
sum
is incremented by n
n
is decremented Upvotes: 3