In computer programming, a sentinel value (also referred to as a flag value, trip value, rogue value, signal value, or dummy data) is a special value whose presence guarantees termination of a loop that processes structured (especially sequential) data. The sentinel value makes it possible to detect the end of the data when no other means to do so (such as an explicit size indication) is provided. The value should be selected in such a way that it is guaranteed to be distinct from all legal data values, since otherwise the presence of such values would prematurely signal the end of the data.
Below are some examples of common sentinel values and their uses:
- Null character for indicating the end of a null-terminated string
- Null pointer for indicating the end of a linked list
- A negative integer for indicating the end of a sequence of non-negative integers
- End-of-file, a non-character value returned by certain input routines to signal that no further characters are available from a file
- High Values, a key value of hexadecimal 0xFF used in business programming
A related practice, used in slightly different circumstances, is to place some specific value at the end of the data, in order to avoid the need for an explicit test for termination in some processing loop, because the value will trigger termination by the tests already present for other reasons. For instance, when searching for a particular value in an unsorted array, every element will be compared against this value, with the loop terminating when equality is found; however to deal with the case that the value should be absent, one must also test after each step for having completed the search unsuccessfully. By placing a copy of the value searched for in an additional slot after the end of the array, an unsuccessful search is no longer possible, and no explicit termination test is required in the inner loop; afterwards one must still decide whether a true match was found, but this test needs to be performed only once rather than at each iteration. Knuth calls the value so placed at the end of the data a dummy value rather than a sentinel.
In safe languages, most uses of sentinel values could be replaced with option types, which enforce explicit handling of the exceptional case.
- Knuth, Donald (1973). The Art of Computer Programming, Volume 1: Fundamental Algorithms (second edition). Addison-Wesley. pp. 213–214, also p. 631. ISBN 0-201-03809-9.
- Knuth, Donald (1973). The Art of Computer Programming, Volume 3: Sorting and searching. Addison-Wesley. p. 395. ISBN 0-201-03803-X.
- McConnell, Steve. "Code Complete" Edition 2 Pg. 621 ISBN - 0-7356-1967-0
|This computer programming–related article is a stub. You can help Wikipedia by expanding it.|