Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Relational operator

From Wikipedia, the free encyclopedia
Programming language construct
"Comparison (computer programming)" redirects here. For comparison of files, seeFile comparison.
"~=" redirects here. For the mathematical usage, seeapproximation. For abstract algebra, seeIsomorphism.
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Relational operator" – news ·newspapers ·books ·scholar ·JSTOR
(March 2022) (Learn how and when to remove this message)

Incomputer science, arelational operator is aprogramming language construct oroperator that tests or defines some kind of relationship between two entities. These include numericalequality (e.g.,5 = 5) andinequalities (e.g.,4 ≥ 3).

In programming languages that include a distinctboolean data type in theirtype system, likePascal,Ada,Python orJava, these operators usually evaluate to true or false, depending on if the conditional relationship between the twooperands holds or not.

In languages such asC, relational operators return theintegers 0 or 1, where 0 stands for false and any non-zero value stands for true.

Anexpression created using a relational operator forms what is termed arelational expression or acondition. Relational operators can be seen as special cases of logicalpredicates.

Equality

[edit]

Usage

[edit]

Equality is used in many programming language constructs and data types. It is used to test if an element already exists in aset, or to access to a value through a key. It is used inswitch statements to dispatch the control flow to the correct branch, and during the unification process in logic programming.

There can be multiple valid definitions of equality, and any particular language might adopt one or more of them, depending on various design aspects. One possible meaning of equality is that "ifa equalsb, then eithera orb can be used interchangeably in any context without noticing any difference". But this statement does not necessarily hold, particularly when taking into account mutability together with content equality.

Location equality vs. content equality

[edit]

Sometimes, particularly inobject-oriented programming, the comparison raises questions ofdata types andinheritance,equality, andidentity. It is often necessary to distinguish between:

  • two different objects of the same type, e.g., two hands
  • two objects being equal but distinct, e.g., two $10 banknotes
  • two objects being equal but having different representation, e.g., a $1 bill and a $1 coin
  • two different references to the same object, e.g., two nicknames for the same person

In many modern programming languages, objects and data structures are accessed throughreferences. In such languages, there becomes a need to test for two different types of equality:

  • Location equality (identity): if two references (A and B) reference the same object. Interactions with the object through A are indistinguishable from the same interactions through B, and in particular changes to the object through A are reflected through B.
  • Content equality: if the objects referenced by two references (A and B) are equivalent in some sense:
  • Structural equality (that is, their contents are the same). which may be either shallow (testing only immediate subparts), or deep (testing for equality of subparts recursively). A simple way to achieve this is through representational equality: checking that the values have the same representation.
  • Some other tailor-made equality, preserving the external behavior. For example, 1/2 and 2/4 are considered equal when seen as a rational number. A possible requirement would be that "A = B if and only if all operations on objects A and B will have the same result", in addition toreflexivity,symmetry, andtransitivity.

The first type of equality usually implies the second (except for things likenot a number (NaN) which are unequal to themselves), but the converse is not necessarily true. For example, twostring objects may be distinct objects (unequal in the first sense) but contain the same sequence of characters (equal in the second sense). Seeidentity for more of this issue.

Real numbers, including many simplefractions, cannot be represented exactly infloating-point arithmetic, and it may be necessary to test for equality within a given tolerance. Such tolerance, however, can easily break desired properties such as transitivity, whereas reflexivity breaks too: theIEEE floating-point standard requires thatNaN ≠ NaN holds. In contrast, the (2022)private standard forposit arithmetic (posit proponents mean to replace IEEE floats) has a similar concept, NaR (Not a Real), whereNaR = NaR holds.[1]

Other programming elements such as computable functions, may either have no sense of equality, or an equality that is uncomputable. For these reasons, some languages define an explicit notion of "comparable", in the form of a base class, an interface, a trait or a protocol, which is used either explicitly, by declaration in source code, or implicitly, via the structure of the type involved.

Comparing values of different types

[edit]

InJavaScript,PHP,VBScript and a few otherdynamically typed languages, the standard equality operator follows so-calledloose typing, that is it evaluates totrue even if two values are not equal and are of incompatible types, but can becoerced to each other by some set of language-specific rules, making the number 4 compare equal to the text string "4", for instance. Although such behaviour is typically meant to make the language easier, it can lead to surprising and difficult to predict consequences that many programmers are unaware of. For example, JavaScript's loose equality rules can cause equality to be intransitive (i.e.,a == b andb == c, buta != c), or make certain values be equal to their own negation.[2]

A strict equality operator is also often available in those languages, returning true only for values with identical or equivalent types (in PHP,4 === "4" is false although4 == "4" is true).[3][4] For languages where the number 0 may be interpreted asfalse, this operator may simplify things such as checking for zero (asx == 0 would be true for x being either 0 or "0" using the type agnostic equality operator).

Ordering

[edit]

Greater than andless than comparison of non-numeric data is performed according to a sort convention (such as, for text strings,lexicographical order) which may be built into the programming language and/or configurable by a programmer.

When it is desired to associate a numeric value with the result of a comparison between two data items, saya andb, the usual convention is to assign −1 if a < b, 0 if a = b and 1 if a > b. For example, the C functionstrcmp performs athree-way comparison and returns −1, 0, or 1 according to this convention, andqsort expects the comparison function to return values according to this convention. Insorting algorithms, the efficiency of comparison code is critical since it is one of the major factors contributing to sorting performance.

Comparison of programmer-defineddata types (data types for which the programming language has no in-built understanding) may be carried out by custom-written or library functions (such asstrcmp mentioned above), or, in some languages, byoverloading a comparison operator – that is, assigning a programmer-defined meaning that depends on the data types being compared. Another alternative is using some convention such as member-wise comparison.

Logical equivalence

[edit]

Though perhaps unobvious at first, like thebooleanlogical operators XOR, AND, OR, and NOT, relational operators can be designed to havelogical equivalence, such that they can all be defined in terms of one another. The following four conditional statements all have the same logical equivalenceE (either all true or all false) for any givenx andy values:

E={x<yy>xxyyx{\displaystyle E={\begin{cases}x<y\\y>x\\x\ngeq y\\y\nleq x\end{cases}}}

This relies on the domain beingwell ordered.

Standard relational operators

[edit]

The most common numerical relational operators used in programming languages are shown below. StandardSQL uses the same operators as BASIC, while many databases allow!= in addition to<> from the standard. SQL follows strictboolean algebra, i.e. doesn't useshort-circuit evaluation, which is common to most languages below. E.g.PHP has it, but otherwise it has these same two operators defined as aliases, like many SQL databases.

Common relational operators
Conventionequal tonot equal togreater thanless thangreater than
or equal to
less than
or equal to
In print=><
FORTRAN[note 1].EQ..NE..GT..LT..GE..LE.
ALGOL 68[note 2]=><
/=>=<=
eqnegtltgele
APL=><
BASIC,ML,Pascal[note 3]=<>[note 4]><>=<=
C-like[note 5]==!=><>=<=
MUMPS='=><'<'>
Lua==~=><>=<=
Erlang==/=><>==<
=:==/=
Bourne-likeshells[note 6]-eq-ne-gt-lt-ge-le
Batch fileEQUNEQGTRLSSGEQLEQ
ooRexx,REXX=¬=><>=<=
\=
<>
MATLAB[note 7]==~=><>=<=
eq(x,y)ne(x,y)gt(x,y)lt(x,y)ge(x,y)le(x,y)
Fortran 90,[note 8]Haskell==/=><>=<=
Mathematica[5]==!=><>=<=
Equal[x,y]Unequal[x,y]Greater[x,y]Less[x,y]GreaterEqual[x,y]LessEqual[x,y]
  1. ^Including FORTRAN II, III, IV, 66 and 77.
  2. ^ALGOL 68:stropping regimes are used in code on platforms with limited character sets (e.g., use>= orGE instead of), platforms with noboldemphasis (use'ge'), or platforms with onlyUPPERCASE (use.GEor'GE').
  3. ^IncludingALGOL,Simula,Modula-2,Eiffel,SQL,spreadsheet formulas, and others.
  4. ^Modula-2 also recognizes#
  5. ^IncludingC,C++,C#,Go,Java,JavaScript,Perl (numerical comparison only),PHP,Python,Ruby, andR.
  6. ^IncludingBourne shell,Bash,KornShell, andWindows PowerShell. The symbols< and> are usually used in a shell forredirection, so other symbols must be used. Without the hyphen, is used inPerl for string comparison.
  7. ^MATLAB, although in other respects using similar syntax as C, does not use!=, as! in MATLAB sends the following text as a command line to theoperating system. The first form is also used inSmalltalk, with the exception of equality, which is=.
  8. ^Including FORTRAN 95, 2003, 2008 and 2015.

Other conventions are less common:Common Lisp andMacsyma/Maxima use Basic-like operators for numerical values, except for inequality, which is/= in Common Lisp and# in Macsyma/Maxima. Common Lisp has multiple other sets of equality and relational operators serving different purposes, includingeq,eql,equal,equalp, andstring=.[6] OlderLisps usedequal,greaterp, andlessp; and negated them usingnot for the remaining operators.

Syntax

[edit]

Relational operators are also used in technical literature instead of words. Relational operators are usually written ininfix notation, if supported by the programming language, which means that they appear between their operands (the two expressions being related). For example, an expression in Python will print the message if thex is less thany:

ifx<y:print("x is less than y in this example")

Other programming languages, such asLisp, useprefix notation, as follows:

(>=XY)

Operator chaining

[edit]

In mathematics, it is common practice to chain relational operators, such as in 3 < x < y < 20 (meaning 3 < xand x < yand y < 20). The syntax is clear since these relational operators in mathematics are transitive.

However, many recent programming languages would see an expression like 3 < x < y as consisting of two left (or right-) associative operators, interpreting it as something like(3 < x) < y. If we say that x=4, we then get(3 < 4) < y, and evaluation will givetrue < y which generally does not make sense. However, it does compile in C/C++ and some other languages, yielding surprising result (astrue would be represented by the number 1 here).

It is possible to give the expressionx < y < z its familiar mathematical meaning, and some programming languages such as Python andRaku do that. Others, such as C# and Java, do not, partly because it would differ from the way most other infix operators work in C-like languages. TheD programming language does not do that since it maintains some compatibility with C, and "Allowing C expressions but with subtly different semantics (albeit arguably in the right direction) would add more confusion than convenience".[7]

Some languages, likeCommon Lisp, use multiple argument predicates for this. In Lisp(<= 1 x 10) is true when x is between 1 and 10.

Confusion with assignment operators

[edit]
See also:Assignment (computer science) § Assignment versus equality

Early FORTRAN (1956–57) was bounded by heavily restricted character sets where= was the only relational operator available. There were no< or> (and certainly no or). This forced the designers to define symbols such as.GT.,.LT.,.GE.,.EQ. etc. and subsequently made it tempting to use the remaining= character for copying, despite the obvious incoherence with mathematical usage (X=X+1 should be impossible).

International Algebraic Language (IAL,ALGOL 58) andALGOL (1958 and 1960) thus introduced:= for assignment, leaving the standard= available for equality, a convention followed byCPL,ALGOL W,ALGOL 68, Basic Combined Programming Language (BCPL),Simula, SET Language (SETL),Pascal,Smalltalk,Modula-2,Ada,Standard ML,OCaml,Eiffel,Object Pascal (Delphi),Oberon,Dylan, VHSIC Hardware Description Language (VHDL), and several other languages.

B and C

[edit]

This uniform de facto standard among most programming languages was eventually changed, indirectly, by a minimalist compiled language namedB. Its sole intended application was as a vehicle for a first port of (a then very primitive)Unix, but it also evolved into the very influentialC language.

B started off as a syntactically changed variant of the systems programming languageBCPL, a simplified (and typeless) version ofCPL. In what has been described as a "strip-down" process, theand andor operators of BCPL[8] were replaced with& and| (which would later become&& and||, respectively.[9]). In the same process, the ALGOL style:= of BCPL was replaced by= in B. The reason for all this being unknown.[10] As variable updates had no special syntax in B (such aslet or similar) and were allowed in expressions, this non standard meaning of the equal sign meant that the traditional semantics of the equal sign now had to be associated with another symbol.Ken Thompson used the ad hoc== combination for this.

As a small type system was later introduced, B then became C. The popularity of this language along with its association with Unix, led to Java, C#, and many other languages following suit, syntactically, despite this needless conflict with the mathematical meaning of the equal sign.

Languages

[edit]

Assignments in C have avalue and since any non-zero scalar value is interpreted astrue inconditional expressions,[11] the codeif (x = y) is legal, but has a very different meaning fromif (x == y). The former code fragment means "assigny tox, and if the new value ofx is not zero, execute the following statement". The latter fragment means "if and only ifx is equal toy, execute the following statement".[12]

intx=1;inty=2;if(x=y){/* This code will always execute if y is anything but 0*/printf("x is %d and y is %d\n",x,y);}

ThoughJava andC# have the same operators as C, this mistake usually causes a compile error in these languages instead, because the if-condition must be of typeboolean, and there is no implicit way to convert from other types (e.g., numbers) intobooleans. So unless the variable that is assigned to has typeboolean (or wrapper typeBoolean), there will be a compile error.

In ALGOL-like languages such as Pascal, Delphi, and Ada (in the sense that they allownested function definitions), and inPython, and many functional languages, among others, assignment operators cannot appear in anexpression (includingif clauses), thus precluding this class of error. Some compilers, such asGNU Compiler Collection (GCC), provide a warning when compiling code containing an assignment operator inside an if statement, though there are some legitimate uses of an assignment inside an if-condition. In such cases, the assignment must be wrapped in an extra pair of parentheses explicitly, to avoid the warning.

Similarly, some languages, such asBASIC use just the= symbol for both assignmentand equality, as they are syntactically separate (as with Pascal, Ada, Python, etc., assignment operators cannot appear in expressions).

Some programmers get in the habit of writing comparisons against a constant in the reverse of the usual order:

if(2==a){/* Mistaken use of = versus == would be a compile-time error */}

If= is used accidentally, the resulting code is invalid because 2 is not a variable. The compiler will generate an error message, on which the proper operator can be substituted. This coding style is termed left-hand comparison, orYoda conditions.

This table lists the different mechanisms to test for these two types of equality in various languages:

LanguagePhysical equalityStructural equalityNotes
ALGOL 68a :=: borais ba = bwhena andb are pointers
C,C++a == b*a == *bwhena andb are pointers
C#object.ReferenceEquals(a, b)a.Equals(b)The== operator defaults toReferenceEquals, but can beoverloaded to performEquals instead.
Common Lisp(eq a b)(equal a b)
Erlanga =:= ba == bwhen a and b are numbers
Goa == breflect.DeepEqual(*a, *b)when a and b are pointers
Javaa == ba.equals(b)
JavaScripta === ba == bwhen a and b are two string objects containing equivalent characters, the === operator will still return true.
OCaml,Smalltalka == ba = b
Pascala^ = b^a = b
Perl$a == $b$$a == $$bwhen$a and$b are references to scalars
PHP$a === $b$a == $bwhen$a and$b are objects
Pythona is ba == b
Rubya.equal?(b)a == b
Scheme(eq? a b)(equal? a b)
Swifta === ba == bwhen a and b have class type
Visual Basic .NET[inequality 1]a Is b orobject.ReferenceEquals(a, b)a = b ora.Equals(b)Same as C#
Objective-C (Cocoa,GNUstep)a == b[a isEqual:b]whena andb are pointers to objects that are instances ofNSObject
  1. ^Patent application: On May 14, 2003,US application 20,040,230,959  "IS NOT OPERATOR" was filed for theISNOT operator by employees ofMicrosoft. This patent was granted on November 18, 2004.

Ruby usesa === b to mean "b is a member of the set a", though the details of what it means to be a member vary considerably depending on the data types involved.=== is here known as the "case equality" or "case subsumption" operator.

See also

[edit]

Notes and references

[edit]
  1. ^Standard for Posit Arithmetic (2022)
  2. ^Denys, Dovhan."WTFJS".GitHub. RetrievedJuly 25, 2024.
  3. ^"Comparing Objects".PHP Manual. PHP Group. RetrievedJune 29, 2014.
  4. ^"PHP: Comparison Operators - Manual". RetrievedJuly 31, 2008.
  5. ^Relational and Logical Operators ofMathematica
  6. ^"Why are there so many ways to compare for equality?".Stack Overflow. RetrievedJuly 25, 2024.
  7. ^Alexandrescu, Andrei (2010).The D Programming Language. Addison Wesley. p. 58.ISBN 978-0-321-63536-5.
  8. ^Used not only in ALGOL-like languages, but also in FORTRAN and BASIC
  9. ^As some programmers were confused by the dual meanings (bitwise operator, and logical connective) of these new symbols (according toDennis Ritchie). Only the bitwise meaning of & and | were kept.
  10. ^AlthoughDennis Ritchie has suggested that this may have had to do with "economy of typing" as updates of variables may be more frequent than comparisons in certain types of programs
  11. ^A zero scalar value is interpreted as false while any non-zero scalar value is interpreted as true; this is typically used with integer types, similar toassembly language idioms.
  12. ^Brian Kernighan and Dennis Ritchie (1988) [1978].The C Programming Language (Second ed.). Prentice Hall., 19
Retrieved from "https://en.wikipedia.org/w/index.php?title=Relational_operator&oldid=1300603770"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp