3

I would like to know the execution flow of compound assignments in C++. I came across a CodeChef question, where I am calculating NCR mod p values and adding them together to get the final answer:

// correct
for(int i=min1; i<=max1; i+=2){
     ans = (ans+ncr_mod_p(n,i))%mod;
}
// incorrect
for(int i=min1; i<=max1; i+=2){
     ans+=ncr_mod_p(n,i)%mod;
}

This is happening because of integer overflow.

So, what is the execution sequence of compound assignment?

Let's say, if we have an equation a+=b%c then what would be the execution sequence:

a = (a+b)%c
// OR
a = a+(b)%c;
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Rahul
  • 1,858
  • 1
  • 12
  • 33

2 Answers2

6

The compound assignment operators are in the second lowest precedence group of all in C++ (taking priority over only the comma operator). Thus, your a += b % c case would be equivalent to a += ( b % c ), or a = a + ( b % c ).

This explains why your two code snippets are different. The second:

    ans+=ncr_mod_p(n,i)%mod;

is equivalent to:

    ans = ans + ( ncr_mod_p(n,i) % mod );

Which is clearly different from the first (correct) expression:

    ans = ( ans + ncr_mod_p(n,i) ) % mod;
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
5

This statement

ans+=ncr_mod_p(n,i)%mod;

is equivalent to the statement

ans = ans + ( ncr_mod_p(n,i)%mod );

As you can see it differs from the statement

ans = (ans+ncr_mod_p(n,i))%mod;

From the C++ 14 Standard (5.18 Assignment and compound assignment operators)

7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335