-4

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

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
James
  • 383
  • 1
  • 4
  • 15

3 Answers3

4

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.

Slava
  • 43,454
  • 1
  • 47
  • 90
2

The following 2 symbols: = and /= are assignment operators. They are used to set the variable on the right to the value or variable on the right. The = operator is simple; it does no operation on the value on the left. So, if we have a statement like:

int x = 5;

The equality assignment operator here simply sets x to 5.

The second operator in the line of code you are confused about is a part of the compound assignment operator group. This operator does 2 operations: it first takes the value stored in the variable on the left side of the operator, divides it by the value on the right side of the operator, and stores it again in the variable on the left side of the operator. Therefore, if we take this simple piece of code:

int y = 25;
y /= 5;

This piece of code declares a variable of type int, initialized to 25. The second line divides the value of y by 5, ad updates the variable y with the resulting value of the mathematical operation.

Now, we are not restricted to having a fixed value, a variable, or a function's return value as a statement on the right side of the assignment operator. We can very well evaluate an expression (like here we do y[i] /= ((double)/n), and then assign the updated value of y[i] to x[i]. The compiler merely evaluates the expression on the right first, and then moves on to assign it to the left-hand variable.

Now, having this explaination, we can summarize this line very easily:

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

The compiler divides the value of y[i] by the value n, casted as a double (unrequired here as y itself is of type double), assigns the new value to y[i], and then assigns x[i] the updated value of y[i].

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
1

Both are assignment operators and assignment operators are evaluated from right to left. Therefore (assuming that n != 0) the combined assignment does the same as this:

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

And of course the first statement can also be written as:

y[i] = y[i] / ((double)n);
Frank Puffer
  • 8,135
  • 2
  • 20
  • 45