Search code examples
c#multiplicationcompound-assignment

Getting wrong result when using Compound multiplication statement - C#


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?


Solution

  • 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)