Thursday, August 07, 2014

Why You Need Parentheses

A friend posted the following image on Facebook. You’ve probably seen like it. Actually I have posted similar myself.
math puzzle
The result, as you might expect, was people arguing over the answer. Is it 9 or is it 1? Obviously it is. Smile
I wrote some code.
            double x = 6 / 2 * (1 + 2);
            button1.Text = x.ToString();
Actually I wrote it twice. Above in C# and below in Visual Basic. Not that there is a lot of difference or course. And they both probably translate to the same intermediate code (MSIL).

        Dim x As Double
        x = 6 / 2 * (1 + 2)
        Button1.Text = x.ToString()

As I expected, the result showed as 9. The addition happens first because of the parentheses. Next the operations start on the left and move right. So 6 is divided by 2 and that result (3) is multiplied by 3 (the result of 1 + 2). But while the computer thinks that way not all people do.

For many people the obvious next operation after the addition is to multiple that result by the 2 before dividing. And there is some logic to that. One would like to think it didn’t make a difference. But of course it does.

Moving from left to right is common practice and it makes things consistent but there is no law of nature that says it has to be that way. This is the sort of sloppy coding that confuses a lot of people. The question should probably be written ( 6 / 2) * (1 + 2) to remove ambiguity. That would remove the confusion. It is a better coding practice even though it just states what we’d like to think is obvious. In real life what is obvious to one person is not always obvious to another.

When writing code a developer owes it to the people who will later have to work with their code (even if it may be themselves) to remove as much ambiguity as possible. Things should be clear to both the computer and other people.

1 comment:

Mike Zamansky said...

One of the reasons I like using scheme early -- with prefix...

Order of operation? We ain't got no order of operations. We don't need no order of opreations. I don't have to show you any stinkin' order of operations!