Search code examples
c#operator-precedence

Operator precedence in C#


Is

(int)(int1 / (float)var2.Count() * 100)

equivalent to

(int)((int1 / (float)var2.Count()) * 100)

...and will it use floating point or integer division?

Edit... if the answer is yes to the above, what is the advantage of performing a floating point division here?


Solution

  • / and * have the same operator precedence, under §7.2.1 so the two results should be the same (using float rules).

    I, however, can't be bothered to learn precedence tables; I just use brackets. Then it works in any language without needing to remember it.

    Another important question is the rounding in the final (int) cast: do you expect that to be "up", "down" or "bankers"?