Clarification on /= operator

James picture James · Mar 7, 2017 · Viewed 9k times · Source

In the following code

#include <iostream>
using namespace std;

int main(void){

  double *x, *y;
  unsigned long long int n=2;

  x = new double [2];
  y = new double [2];

  for(int i=0; i<2; i++){
    x[i] = 1.0;
    y[i] = 1.0;
    //what is the following line doing exaclty? 
    x[i] = y[i]/=((double)n);
    cout << "\n" << x[i] << "\t" << y[i];
  }

  delete [] x;
  delete [] y;

  printf("\n");
  return 0;

}

I do not understand what the combination of = and /= is doing exactly, and why this is allowed (the code compiles and runs correctly under Valgrind).

Answer

Slava picture Slava · Mar 7, 2017

This code

 x[i] = y[i]/=((double)n);

is logically equivalent to this 2 lines:

 y[i]/=((double)n);
 x[i] = y[i];

and first line is logically equal to:

 y[i] = y[i] / n;

note typecasting here is completely redundant.