Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 546
Ben Aston Avatar asked Jul 19 '10 09:07

Ben Aston


People also ask

What is operator precedence in C?

The precedence of operators in C dictates the order in which the operators will be evolved in an expression. Associativity, on the other hand, defines the order in which the operators of the same precedence will be evaluated in an expression. Also, associativity can occur from either right to left or left to right.

What is an precedence of operators?

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.

Which is the highest operator precedence in C?

Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

What is the priority among (* %) (+ -) and (=) C operators?

1) What is the Priority among (*, /, %), (+, -) and (=) C Operators.? Explanation: Assignment operator in C has the least priority.


1 Answers

/ 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"?

like image 141
Marc Gravell Avatar answered Oct 07 '22 16:10

Marc Gravell