Search code examples
basic

On use of parenthesis


So I was looking over some A-Levels Computer Science past papers, and stumbled into this:

enter image description here

Now, my first reaction was that there is no need for parenthesis on line 6. Reason being that algebraic operators take precedence over comparisons which take precedence over boolean ones.

As a small example from Java:

        int a = 100;
        int b = 100;
        int c = 100;
        int d = 100;

        if( ((c+d) > 180) && ((a+b+c+d)) >= 320)
            System.out.println("greater");

        if(c+d > 180 && a+b+c+d >=320)
            System.out.println("greateragain");

Both if statements are evaluated to true.

So, am I right in thinking parenthesis are only for human readability in this case or...?


Solution

  • You can say: "The use of parentheses makes the precendence of evaluation explicit, disregarding of the operator precendence of the language in use."

    The comments above describe well that operator precendence is language specific. For example, in Pascal, logical operators such as AND seem to have higher precendence than math operators, and interpreted as binary AND. In contrast in C, the && has lower precedence, hence you can save some parentheses.

    Therefore, it sounds like a wise idea to always use parentheses in case of a possible ambiguity, or at least until you're mastering the language in use.