1

Why does TestAddition result in 12 instead o 13? It should be 5 + 1 + 7 = 13, but assert fails with

Expected: 13

But was: 12

int method(int a)
{
    return 7;
}

[Test]
public void TestAddition()
{
    int row = 5;
    row += method(++row);

    Assert.AreEqual(13, row, "Why is it twelve instead of 13?");
}
Community
  • 1
  • 1
jahav
  • 699
  • 1
  • 7
  • 24
  • [C# Pre- & Post Increment confusions](http://stackoverflow.com/questions/8573190/c-sharp-pre-post-increment-confusions) – Jason Evans Nov 14 '15 at 14:30

2 Answers2

3

Because your

row += method(++row);

equals to

row = row + method(++row);

Since + operator is left associative, it calculates first row as a 5 and method always return 7 no matter which parameter it takes.

row = row + method(++row);
       ^          ^
       5          7

That's why result will be 12.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1
row += method(++row);

is the same as

row = row + method(++row);

The operands are evaluated from left to right, so the value of the left operand (row) is evaluated before row is incremented in method(++row).

The expected result is 12.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39