Question

I want to know what is the better way to reset a counter. I have the following:

03 WS-SEQ-NO    PIC  9(04).

When WS-SEQ-NO is 9999, and i increment it, or if i move 10000 into it, it will get truncated, and become 0000. This is actually the desired result as i want it to tick over to 0000 after 9999. However, i am interested to know if this is acceptable by COBOL programming standards? Or should i be using an IF condition to reset it. E.g:

IF WS-SEQ-NO = 9999
    MOVE 0 TO WS-SEQ-NO
ELSE
    ADD 1 TO WS-SEQ-NO
END-IF.

Also, this code will only be executed once a month or so, and it is not in a loop, so i'm not desperate to avoid having the additional IF condition. I'm merely wondering if it is 'legal', so to speak, in a programming standards sense, to rely on this COBOL feature that truncates the number rather than coding for it. Thanks!

Was it helpful?

Solution

I would keep the condition and define the counter this way

01 COUNTERS.
   03 WS-SEQ-NO    PIC  9(04).
      88 MAX-SEQ-NO VALUE 9999.
...
IF MAX-SEQ-NO
    MOVE 0 TO WS-SEQ-NO
ELSE
    ADD 1 TO WS-SEQ-NO
END-IF.

If you need to modify your counter to PIC 9(5), you won't forget to modify the condition because you won't have to.

You'll only need to modify the level 88.

OTHER TIPS

I much prefer to see the "Move 0 to WS-SEQ-NO". Relying on rollover might not work as expected on all platforms, and it simply isn't as clear.

Remember, you write the source code for the humans that come after you. They should look at it and clearly see "oh, reset the counter".

I find the MOVE 0 TO WS-SEQ-NO method to be clearer as to your intent.

Something to keep in mind, there may be compile options that affect the truncation/rollover behavior you observe. For example, in IBM's Enterprise COBOL, if WS-SEQ-NO is defined as PIC 9(4) COMP then the compile option TRUNC(BIN) will cause truncation/rollover at 65535, while TRUNC(STD) will exhibit the behavior you're currently seeing.

I know COBOL from nothing, but my concerns would be that the data type used for WS-SEQ-NO might be different with a different implementation of COBOL, and could change size so that an automatic roll-over would no longer work. More importantly, the if statement makes it perfectly clear that this is what you intend and is not merely an accidental side effect.

If it works, it works. However, add comments to your program in working-storage and in the program's loop to say that you are expecting rollover to occur and that is the desired outcome. Us mortals won't know that next year when we are doing maintenance to your program and we will hunt you down.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top