Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.