TechQuiz Question 8: On precedence and operators

What is the output of the following program?

class Program
{
    static void Main()
    {
        int result = x() + y() *
        Console.WriteLine(result
    }
    static int x()
    {
        Console.WriteLine(“x”);
        return 3;
    }
    static int y()
    {
        Console.WriteLine(“y”);
        return 2;
    }
    static int z()
    {
        Console.WriteLine(“z”);
        return 6;
    }
}

Answer


We all know that multiplication has a higher precedence then addition. 
So for example: 3 + 2 * 3 will be calculated as 3 + (2 * 3) = 3 + 6 = 9.
The result of our simple program is also not very hard to calculate. 3 + (2 * 6) = 15. So, y and z before x. The expected output would be: y z x 15. Or not?

As you can see, the output is x y z 15. Why is that? It’s because operator precedence controls the order in which operators are executed, not the order in which they are evaluated!
Operands are evaluated from left to right. So x is evaluated before y and y is evaluated before z. Then the resulting values are executed, which uses the normal operator precedence we are used to.
In something simple as this, it won’t cause any problems. But suppose that x, y, z act on some class fields and modify them. Then suddenly, your fields would be modified ‘left to right’ and then the result would be calculated with regular operator precedence.
This question originated while reading The C# Programming Language, 4th Edition. Thanks to Eric Lippert for his annotation about precedence!

Wouter de Kort works as a lead architect and consultant. He helps organizations stay on the cutting edge of software development. Wouter focuses on DevOps. He loves solving complex problems and helping other developers to grow. Wouter authored the book DevOps on the Microsoft stack and a couple of other books. Wouter is a Microsoft MVP and an ALM Ranger. You can find him on Twitter (@wouterdekort), on his blog at wouterdekort.com and at the various conferences where Wouter speaks.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.