提出问题提出问题
 

建议的答复operators precedence

  • 2006年10月11日 16:18CoverPpl 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     

    why is that i the operators precedence of c# its seems like (x++) will be execute before (++x)? is it true?

    which is the highest operator precedence here --> (++x),(x++),<<    ?

    thanks in advanced

     

全部回复

  • 2006年10月11日 16:25Mark Rendle 用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     

    ++x increments x and then "returns" its value.

    x++ "returns" the value and then increments x

    So

    int x = 0;
    Console.WriteLine(x++); // Outputs 0
    Console.WriteLine(x); // Outputs 1

    x = 0;
    Console.WriteLine(++x); // Outputs 1
    Console.WriteLine(x); // Outputs 1

  • 2006年10月11日 16:32TaylorMichaelLMVP, 版主用户奖牌用户奖牌用户奖牌用户奖牌用户奖牌
     建议的答复

    As Mark said the operators perform two different tasks so oftentimes this accounts for the behavioral problems that people see.  If you are ever concerned about the precedence of operators you should probably refactor your code (by adding parenthesis) as others will be confused to.

    As for precedence postfix increment and decrement (x++, x--) are higher precedence than prefix (++x,--x).  They are at the same level as function calls, array indexing, field referencing and a few other operators.  Prefix operators are with the unary plus and minus operators, negation, not and typecasts.  Again, if you are unsure of the precedence then use parenthesis to make it clear.

    As for the original question as to why this is it is because the C# designers wanted to follow the rules of C++.  Why did the C++ designers set it this way?  Because they wanted to follow C.  Why did the C designers set it this way?  Technically they didn't.  The C (or C++) standards leave the order of operator evaluation as undefined meaning that each compiler can evaluate expressions in whatever order they want. 

    Now before anybody starts pointing to precedence charts in their favorite C/C++ book please take a moment to look at the C or C++ standards.  Precedence isn't defined other than as how the topics are covered in the spec.  However the specs do specify the grammars that must compile.  It is in these grammar rules where operator precedence is set up.  Way down deep in an expression rule you'll find that postfix expressions are evaluated before prefix expressions.  This means they have higher precedence.  Therefore, unlike some languages, C/C++ define the operator precedence in the grammar rules rather than as specific hierarchies in the specification.  As a result you can build a precedence table given the grammar rules.  Why exactly the C designers felt postfix was higher than prefix I don't know.

    Michael Taylor - 10/11/06