Operator Evaluation parentheses - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Operator Evaluation parentheses

wcx950wcx950 Posts: 3Member
I am a little confused about using the correct amount of parentheses around operators.

For example, which one of these would be correct:

1. if (length(s) >= 2) and (s[1] = 'A') or (s[1] = 'B') then ...
2. if (length(s) >= 2) and ((s[1] = 'A') or (s[1] = 'B')) then ...


I am assuming 2. is the correct method, but I want to be sure. They seem to both function correctly, though...

Comments

  • zibadianzibadian Posts: 6,349Member
    : I am a little confused about using the correct amount of parentheses around operators.
    :
    : For example, which one of these would be correct:
    :
    : 1. if (length(s) >= 2) and (s[1] = 'A') or (s[1] = 'B') then ...
    : 2. if (length(s) >= 2) and ((s[1] = 'A') or (s[1] = 'B')) then ...
    :
    :
    : I am assuming 2. is the correct method, but I want to be sure. They seem to both function correctly, though...
    :
    They both work, although differently. The first is actually this:
    [code]
    if ((length(s) >= 2) and (s[1] = 'A')) or (s[1] = 'B') then ...
    [/code]
    This is because the AND and OR are on the same priority level, mathematically speaking. Thus they are evaluated from left to right.
    As to the question, which is correct, that depends on what you want to evaluate. If you want your strings to have a length of 2+ and (start with either A or B) the second is correct. The first is correct if string may be (length of 2+ and start with A) or (any length and start with B).
Sign In or Register to comment.