-2

How does C# execute this?

static void Main(string[] args)
    {

        int i = 4;

        i *= 4 + 8 / 2;
        Console.WriteLine(i);
    }

This was asked in one of the interview Questions. And I applied BODMAS to it. But it was wrong. Please Explain.

Al Lelopath
  • 6,448
  • 13
  • 82
  • 139
Prateik
  • 241
  • 2
  • 6
  • 14

3 Answers3

0

It will be executed equivalent to the following code:

int i = 4;
int temp = 8 / 2;
temp = 4 + temp;
i = i * temp;

The compiler will shorten it down because it can calculate the constant that is on the right of i *=, so in reality it will compile to this:

int i = 4;
i *= 8;
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
0

i *= 4 + 8 / 2 is executed as:

i = i * (4 + (8 / 2))

That's the correct way of reading it.

jim
  • 1,153
  • 1
  • 7
  • 9
0

Operator precedence is very clear on this: The / is a multiplicative operator and is applied first, then the +. The *= is an assignment operator and is applied last.

So:

8 / 2 = 4
4 + 4 = 8
i *= 8;
so i will be 4 * 8 = 32;
Dennis_E
  • 8,751
  • 23
  • 29