Using Parentheses


Items enclosed in parentheses are evaluated first. Use parentheses to clarify as well as to group operations.

Order of Operations for Arithmetic (p. 111)

  1. Items enclosed in parentheses
  2. Exponentiation
  3. Multiplication and Division (from left to right)
  4. Addition and Subtraction (from left to right)

Hierarchy of Operations (p. 201)

  1. Arithmetic
  2. Relational
  3. NOT
  4. AND (from left to right)
  5. OR (from left to right)

Examples

The COMPUTE statement on the left is equivalent to the one on the right. The parentheses used in the statement on the right clarify (but do not change) the logic. Thus, the statement on the right is easier to comprehend.

COMPUTE X = A + B * C. COMPUTE X = A + ( B * C ).
COMPUTE X = A * B ** C. COMPUTE X = A * ( B ** C ).
COMPUTE X = A + B - C. COMPUTE X = ( A + B ) - C.
COMPUTE X = A + B - C * D / E ** F. COMPUTE X = ( A + B ) - ( ( C * D ) / ( E ** F ) ).
COMPUTE X = A + B / C * D. COMPUTE X = A + ( ( B / C ) * D ).

Parentheses may be used not only to clarify the logic but also to alter the order of operations.

Given A = 4, B = 3, C = 2, D = 1
COMPUTE X = A + B * C. X = 10 COMPUTE X = ( A + B ) * C. X = 14
COMPUTE X = A + B ** C. X = 13 COMPUTE X = ( A + B ) ** C. X = 49
COMPUTE X = A + B / C * D. X = 5.5 COMPUTE X = ( A + B ) / ( C * D ). X = 3.5

Parentheses are also useful in clarifying or modifying AND-OR logic in IF statements.

1. IF X AND Y OR Z
2. IF ( X AND Y ) OR Z
3. IF X AND ( Y OR Z )

Statements 1 and 2 are equivalent. But, the parentheses in statement 2 make the code easier to understand. The parentheses in statement 3 alter the logic.


Cobol Home