Search code examples
c#operator-precedencepost-incrementpre-increment

Forcing arithmetic precedence with syntactic sugar


Every morning I get up grab my coffee and head on to SO to see what John Skeet has answered the day before. It's my daily reminder that how much I don't know. Today, for this question there was a discussion on the increment operators such as ++ and --. The MSDN doc says that ++ and -- have higher precedence than *. Consider this code:

         int c = 10;
         c = c++ * --c;

and this code

        int c = 10;
        c = (c++) * (--c);

in both cases c is 100. How would you force precedence (if possible at all) on this so the values in the parenthesis will be evaluated first before the multiplication?


Solution

  • The ++ after the variable will be applied only after the current instruction because it is a post increment. Use ++ or -- before a variabile to achieve what you want

    int c = 10;
    c = ++c * --c ;
    Console.WriteLine ( c ) ;
    

    This code will output 110 because 10 + 1 = 11 and 11 - 1 = 10 so 10 * 11 = 110