What is the purpose of this: "double x = x = (a - b) / (c - 1);"

I came across this code in which a variable is assigned to itself without a good reason.

double x = x = (a - b) / (c - 1); 

That doesn't make much sense to me. Is there a reason for this?

+6
source share
3 answers

When assigning several variables at once, all variables will receive the value of the right operand. Performing this double assignment does not give any value; it will probably even be optimized for double x = (a - b) / (c - 1); the compiler. This is definitely a typo.

+6
source

His typo . There is no reason to reassign value to yourself in your case.

Side note: However, if you just write

 double x = x; 

Then the compiler also gives a warning :

enter image description here

In your case, it will take the value from the right operand and therefore it will be compiled and there will be no problems, but it does not make any real sense. Perfect demonstration

+3
source

If such a construction can make sense when you want to assign one value to several variables :

 double x, y; x = y = 42; 

Now you have two variables initialized with the same value, because the result of the expression of the assignment expression ( y = 42 ) is the value that was assigned ( 42 ) .

However, in its current form (or from the original source, as you indicated ), as such:

 double spacing = spacing = 42; 

It makes no sense and can be simplified:

 double spacing = 42; 
+1
source

All Articles