1

I noticed something very strange. In the code snippet below, the result outputted on the Console is always 0

int result = 0;
for(int i = 1; i < 4; i++)
{
  result *= 10 + i;
}
Console.WriteLine(result);

It looks like result *= 10 + i; always multiplies 10 to the result (where result is 0) and does not add i to it.

If I change just the multiplication line...

int result = 0;
for(int i = 1; i < 4; i++)
{
  result = result * 10 + i;
}
Console.WriteLine(result);

This outputs the correct result on the Console - that is 123.

My question is, why is result *= 10 + i; not working correctly - and always giving the result as 0?

Luke Willis
  • 8,429
  • 4
  • 46
  • 79
Vikram Singh
  • 435
  • 2
  • 10

1 Answers1

5

This is because of the order of operations.

result = result * 10 + i

is equivalent to...

result = (result * 10) + i

...but...

result *= 10 + i

is the same as...

result = result * (10 + i)
Luke Willis
  • 8,429
  • 4
  • 46
  • 79
  • 1
    And the compound version of `result = result * 10 + i;` is `result *= 10; result += i;` or even `(result *= 10) += i;` – Ben Voigt Jun 15 '21 at 17:29