Lesson 5: Sentinel Values

If you were robbing a house, wouldn't you have a lookout posted to signal you if there were people coming? Okay bad example, but you get the point. Anyway, in Turing, the “lookout” is called a sentinel value.

Sentinel, by definition, means a person or thing that watches or stands as if watching something. A sentinel value is a special value whose presence indicates that a special event has occurred. They are often used to tell the computer that the end of a set of values has been reached. Always use pre–declared sentinel values in exit statements, because otherwise, they would be considered magic values. A program will not be considered well written by serious programmers if it includes any magic values. Always avoid them at all costs!

The following is an example of the use of a sentinel value in a program. Consider the contents of the loop and the content outputted on the run window:

var payroll: real
put "To exit, please enter \"-1\"."
loop
        put "Payroll amount? " ..
        get payroll
        
        exit when payroll = -1
end loop
			

As shown above, the user is prompted for payroll amounts in dollars. This amount is accumulated through the help of an accumulator. When the user has finished inputting his data, somehow, the user must signal to the program that the data has finished being inputted. To do this, we are using the sentinel value -1, as said in the program's intro. This sentinel value is ideal for this situation because, as described soon, it is not a valid input since a user cannot earn $-1!

Whenever you write a program that includes a sentinal value, make sure to inform the user what the actual value is. This would prevent the user from confusion and frustration when the user realizes that he or she would like to exit the loop, however, they do not know the sentinel value. In addition, the sentinel value must follow the rules of programming etiquette and should preferably not be a valid input. For instance, if the “Square Root” program is meant to find the area of a square, then the values of user input should be of a real datatype and of a positive numeric value. This implies that the corresponding sentinel value should follow the same specifications. Always remember to choose a sentinel value that matches the type of character it is. If the variable is a string, the sentinel value must also be a string, as prior mentioned. If it is not possible to choose a sentinel value that is not a valid input, you may:

Valid XHTML 1.0 Strict Valid CSS! Valid CSS!