Reputation: 693
I came across this code in which a variable is assigned to itself for no good reason.
double x = x = (a - b) / (c - 1);
It is not making much sense to me. Is there a reason behind this?
Upvotes: 6
Views: 254
Reputation: 4129
When assigning multiple variables at once all the variables will get the value of the right hand operand. Doing this double assignment does not provide any value, it will probably even be optimzed to double x = (a - b) / (c - 1);
by the compiler. This is definately a typo.
Upvotes: 6
Reputation: 151710
Where a construct like this could make sense is when you want to assign the same value to multiple variables:
double x, y;
x = y = 42;
Now you have two variables initialized with the same value, because the result of an assignment expression (y = 42
) is the value that was assigned (42
).
However, in its current form (or from its original source, as you indicated), as such:
double spacing = spacing = 42;
Makes no sense, and can be simplified:
double spacing = 42;
Upvotes: 1
Reputation: 172578
Its a typo. There is no reason of assigning the value again to itself in your case.
On a side note: However if you simply write
double x = x;
Then the compiler also gives you a warning saying:
In your case it will take the value from the right hand operand and hence it will compile and there will be no issues but it does not make any real sense. Ideone Demo
Upvotes: 3