Often I will encounter the use of - or even use myself - the value -1 as an edge case in otherwise integer data structures. For instance, as the value for "irreplaceable" in a Replacement Cost field.

This is especially useful where null is either unrecognised; semantically overburdened; or converted into empty when migrating data across formats.

What is the formal computer science view on the use of negative integers for non-numeral meanings in data fields which are still used normally for positive integers?


closed as primarily opinion-based by D.W., David Richerby, FrankW, Shaull, lPlant Oct 9 '14 at 3:47

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ This is a question about programming, not about computer science. $\endgroup$ – David Richerby Oct 4 '14 at 6:52
  • $\begingroup$ @DavidRicherby I initially thought that; until I realised I know full well how to code edge cases; but not whether (given the CompSci origins of robust programming), when or if it is appropriate to use -1 or similar in this fashion. For example, a question about GOTO usage starts as, and returns to, a Computer Science foundation. $\endgroup$ – LateralFractal Oct 4 '14 at 9:27

Most PL folks would probably suggest that an option type is better suited.

For instance, in Haskell you'd use a Maybe T type: you use Nothing instead of -1, and Just x instead of x. In SML, you'd use a T option type, and use None instead of -1 and SOME x instead of x.

The benefit of this is to better document the meaning of the sentinel value, and also to force the programmer to consider both cases everywhere it is relevant. This helps avoid certain kinds of programming mistakes, where a -1 value is inadvertently used as if it were a real value. It also ensures that the domain of the type T is separate from the sentinel value.

In a language without an option type, you can also use tagged unions or other methods of encoding this into the type system or class hierarchy.

That said, this is a pretty subjective question. Opinions will vary. You should not expect everyone in a field to share the same opinion about a subjective matter like this.


Not the answer you're looking for? Browse other questions tagged or ask your own question.