Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 768
Kshitiz Kamal Avatar asked Dec 01 '22 09:12

Kshitiz Kamal


1 Answers

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.

like image 141
Bathsheba Avatar answered Dec 04 '22 03:12

Bathsheba