6

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?

Saeid
  • 691
  • 7
  • 26
  • As you can see equation on the right might wind up with a zero denominator. – Saeid Feb 01 '16 at 13:36
  • 1
    There is no good reason -to me at least. You could ask the writer. My bet is on typo... – Thomas Ayoub Feb 01 '16 at 13:39
  • @Thomas: the code is open source by Autodesk: Line 117- https://github.com/AMEE/revit/blob/master/samples/Revit%202012%20SDK/Samples/Reinforcement/CS/BeamGeometrySupport.cs – Saeid Feb 01 '16 at 13:43
  • 1
    Actual code is (still) `double spacing = spacing = (m_beamWidth - 2 * offset) / (rebarNumber - 1);`. Possible explanations, 1. original code had declaration and assignment on separate lines and it was joined by replacing the ; with an = and forgetting to delete redundant assignment, 2. the variable name better describes the author's state of mind (at 2am), 3. it's a double (it's so nice they assigned it twice) |<[;p – Uber Kluger Sep 25 '20 at 07:59

3 Answers3

6

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.

Simon Karlsson
  • 4,090
  • 22
  • 39
  • yeah, I suspect that should be a typo. Was hoping for a better reason though. – Saeid Feb 01 '16 at 13:39
  • Definitely a typo. The second `x =` effectively does nothing. – Matthew Watson Feb 01 '16 at 13:49
  • It's of passing interest if you think about ordering of operations (if x is declared a double then x equals whatever x is set to). I can imagine it tripping people up in interviews. By typo I assume they mean it should be double x = (...) – Tim Barrass Feb 01 '16 at 15:51
3

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:

enter image description here

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

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

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;
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272