0

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--);
Cesar
  • 115
  • 3
  • 10
  • 1
    @both above comments : in C there are many constructs that cannot be found out by experiment, because they are undefined. See http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior. – Quentin Dec 12 '15 at 11:42
  • Yet again, stop. writing. rubbish. code. If it's confusing, why did you write it like that? Why did you not just split it up? – Martin James Dec 12 '15 at 12:00

3 Answers3

6

For sum += n-- the following operations are performed

  • add n to sum
  • decrement n

With sum += --n

  • n is decremented
  • the new value of n is added to sum

n-- is called postdecrement, and --n is called predecrement

alain
  • 11,939
  • 2
  • 31
  • 51
3

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
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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 awas 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

Anish Sharma
  • 495
  • 3
  • 15