질문하기질문하기
 

제안된 답변operators precedence

  • 2006년 10월 11일 수요일 오후 4: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일 수요일 오후 4: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일 수요일 오후 4: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

    • 답변으로 제안됨Matt Pritchard 2009년 9월 15일 화요일 오후 1:30
    •