Cesar
Cesar

Reputation: 115

Order of operations in for loops in C

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

Answers (3)

Anish Sharma
Anish Sharma

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

Upvotes: 0

alain
alain

Reputation: 12047

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

Upvotes: 6

ForceBru
ForceBru

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

Related Questions