Every program needs to "make" decisions at some point.
To achieve this COBOL provides conditional clauses like IF.
Syntax
IF condition (THEN)
PERFORM DO SOMETHING.
ELSE
PERFORM DO SOMETHING ELSE
END IF.
Below a simple program, which displays "Hello World" on the screen, if a user types in "Y".
If a user types in anything else, "You answered No." is displayed.
The comparison in above program is case sensitive.
END-IF is the scope terminator. You could use just a dot (.) as scope terminator, but good coding practice forbids that.
The THEN clause is optional.
Binary Operators
Binary operators are used to combine different conditions. You have the following binary operators available.
- AND
- OR
The following program shows a combination of conditions using binary operators and parenthesis.
NEXT-SENTENCE (DO NOT USE! - DEPRECATED)
This clause can be used to move program execution flow to the next SENTENCE in your program after the closest period below the current IF statement.
Does sound weird, doesn't it.
Don't worry about it. It should not be used anymore, I just mention it for the sake of completeness.
Relational Operators
The syntax is fairly simple.
OPERAND-1 [RELATIONAL OPERATOR] OPERAND-2
A relational operator compares two operands against each other and always returns TRUE or FALSE.
Below an overview on relational operators and examples for their usage. For each operator there is a long and a short version.
Long Version | Short Version |
IF A IS LESS THAN B | IF A < B |
IF A IS GREATER THAN B | IF A > B |
IF A IS EUQAL B | IF A = B |
IF A IS NOT LESS THAN B | IF A NOT < B |
IF A IS NOT GREATER THAN B | IF A NOT > B |
IF A IS NOT EQUAL | IF A NOT = B |
This does not need further explanation.
You can differentiate between numeric and non-numeric comparison, which follows certain rules.
If for example a comparison of numeric and alphanumeric data types works, is compiler dependent.
in GnuCOBOL the below example works just fine.
No need to mention that you should not compare different data types anyway.