Kshitiz Kamal
Kshitiz Kamal

Reputation: 141

Can someone explain how the shorthand assignment operator actually works?

#include <iostream>
using namespace std;
int main()
{   
    int x=2,a=3,b=2;
    x*=a/b;
    cout<<x<<" ";
    x=2;
    x=x*a/b;
    cout<<x;
    return 0;
}

I am getting output as: 2 3 while in my opinion x*=a/b; and x=x*a/b; mean the same thing. Can anybody explain this behaviour?

Upvotes: 4

Views: 205

Answers (4)

Andreas DM
Andreas DM

Reputation: 11018

I am getting output as: 2 3 while in my opinion x*=a/b; and x=x*a/b; mean the same thing. Can anybody explain this behaviour?

x *= a / b;
//   ^^^^^

This is integer division, the rest is discarded and therefore 3 / 2 is 1.
Therefore the expression x *= a / b is the same as x *= 1 which stays 2.

x = x * a / b;

On the other hand is evaluated as

x = (x * a) / b;

The result is then

x = (2 * 3) / 2;

becomes

x = 6 / 2;

which is 3

Upvotes: 4

NathanOliver
NathanOliver

Reputation: 180825

Per [expr.ass]/6 E1 *= E2 is exactly he same as E1 = E1 * E2. That does not mean that x*=a/b; is the same as x=x*a/b;. Since E2 is a/b, x*=a/b; is actually equivalent to x=x*(a/b); which does produce the same results.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234775

They are not quite the same.

x *= a / b is grouped as x *= (a / b) and a / b takes place in integer arithmetic (it's 1).

x = x * a / b is grouped as x = ((x * a) / b). the integer division has a less drastic and different effect.

Upvotes: 6

Jarod42
Jarod42

Reputation: 217750

With integer division: 3/2 is 1.

  • x*=a/b; is evaluated as x *= (a / b) so x *= 3 / 2 -> x *= 1.
  • x=x*a/b; is evaluated as x = (x * a) / b; so (2 * 3) / 3 -> 6 / 2 -> 3

Upvotes: 5

Related Questions