Comparison (computer programming)
From Wikipedia, the free encyclopedia
In computer programming, when one compares the two values x and y, a negative number often indicates x < y, zero x = y and a positive number x > y. Even when two values are not integers, e.g. literal strings, this convention is largely adopted. For example, strcmp
returns -1, 0, or 1 according to the lexicographical order, and qsort expects the comparison function to return values according to this convention. This is because it is efficient to do the subtraction x - y resulting in the directional signs above. In sorting algorithms, the efficiency of comparison code is critical since it is one of the major factors of sorting performance.
Sometimes, particularly in object-oriented programming, the comparison raises questions of datatypes and inheritance, equality and identity. It is often necessary to distinguish between:
- two objects with different datatypes both related to another datatype, e.g. an orange and a lemon, both being citrus fruit
- two different objects of the same type, e.g. two hands
- two objects being equal but distinct, e.g. two $10 banknotes
- two different references to the same object, e.g. two nicknames for the same person
Sameness and difference can be relative or graduated as well as absolute, particularly in fuzzy logic, artificial intelligence, signal processing, lossy data compression and pattern recognition.