Home  >  Article  >  Backend Development  >  Operator precedence in c#

Operator precedence in c#

下次还敢
下次还敢Original
2024-05-09 22:45:28463browse

Priority of operators in C#: unary operator () (positive sign), - (negative sign), ! (logical NOT), ~ (bitwise NOT) * (multiplication), / (division) ), % (remainder) (addition), - (subtraction) < (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to), == (equal to) , != (not equal) && (logical AND), || (logical OR), ^ (logical exclusive OR)?:: (condition? true_expression : false_expression)= (assignment), =, -=, *=, / = (compound assignment)

Operator precedence in c#

The precedence of operators in C

#In C#, the precedence of operators The level determines the order in which expressions are evaluated. The precedence of operators from high to low is:

Unary operator

  • (): Parentheses
  • : Positive sign
  • -: Negative sign
  • !: Logical negation
  • ~: Bitwise notation

Multiplication and division operators

  • *: Multiplication
  • /: Division
  • %: Remainder

Addition and subtraction operators

  • : Addition
  • -: Subtraction

Comparison operator

  • ##<: less than
  • <=: less than or equal to
  • >: greater than
  • >=: greater than or equal to
  • ==: equal to
  • != : Not equal to

Logical operator

    ##&&
  • : Logical AND
  • ||
  • : Logical OR
  • ^
  • : Logical XOR
Conditional operator

    ?:
  • : Condition? true_expression : false_expression
Assignment operator

    =
  • : Assignment
  • =
  • , -=, *=, /=: Compound assignment
Example

The following example illustrates how operator precedence affects the evaluation of an expression:

<code class="csharp">int x = 1 + 2 * 3; // 7
int y = (1 + 2) * 3; // 9</code>

In the first expression, multiplication operator has higher precedence than the addition operator, so the expression first evaluates

2 * 3

before adding the result to 1. In the second expression, the parentheses have higher precedence than the multiplication operator, so the expression first evaluates

1 2

and then compares the result with 3 Multiply.

The above is the detailed content of Operator precedence in c#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does it mean in c#?Next article:What does it mean in c#?