#1,075 – Operator Precedence Doesn’t Affect Operand Evaluation Order

Rules for operator precedence and associativity determine the order in which the operators within an expression will be evaluated.  Parentheses can also change the order in which the operators are evaluated.

For example:

            // * operator evaluated before +
            int sum1 = 1 + 2 * 3;    // 7

            // + operator evaluated first
            int sum2 = (1 + 2) * 3;  // 9

Operands, however, are evaluated from left-right, regardless of the order of evaluation of the operators. For example, in the code below, the sub-expression Return2() * Return3() is evaluated before adding Return1().  But console output shows us that Return1() was executed first.

        static int Return1()
        {
            Console.WriteLine("1");
            return 1;
        }

        static int Return2()
        {
            Console.WriteLine("2");
            return 2;
        }

        static int Return3()
        {
            Console.WriteLine("3");
            return 3;
        }

        static void Main(string[] args)
        {
            // * operator evaluated before +
            int sum1 = Return1() + Return2() * Return3();    // 7
        }

1075-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment