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.
But luckily for us, The C# specification explains it all!
This question originated while reading The C# Programming Language, 4th Edition. Thanks to Eric Lippert for his annotation about precedence!