Relational operator
Encyclopedia
In computer science
, a relational operator is a programming language
construct or operator
that tests or defines some kind of relation
between two entities
. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 ≥ 3). In programming languages that include a distinct boolean data type in their type system
, like Java
, these operators return true or false, depending on whether the conditional relationship between the two operands holds or not. In other languages such as C
, relational operators return the integers 0 or 1.
An expression
created using a relational operator forms what is known as a relational expression or a condition. Relational operators are also used in technical literature instead of words. Relational operators are usually written in infix 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 C will print the message if the x is less than y:
Other programming languages, such as Lisp, use prefix notation, as follows:
Other conventions are less common: Common Lisp
and Macsyma
/Maxima use Basic-like operators except for inequality, which is /= in Common Lisp and # in Macsyma/Maxima. Older Lisp
s used
International Algebraic Language and ALGOL (1958 and 1960) therefore introduced "
, Algol W
, BCPL
, Simula
, Algol 68
, SETL
, Pascal
, Smalltalk
, Modula2, Ada
, Standard ML
, Objective Caml
, Eiffel
, Delphi
, Oberon
, Dylan, VHDL, and several other languages.
On the other hand, the now very influential language C
started off as a minimal compiled language called B, which, in turn, started off as a simplified version of BCPL
(a typeless version of CPL
). The intented application for B was solely as a vehicle for a first port of (a then very primitive) UNIX. In what that has been described as a "strip-down" process, B replaced the original "
x is equal to y, execute the following statement".
Though Java
and C# have the same operators as C, this mistake usually causes a compile error in these languages instead, because the if-condition must be of type boolean, and there is no implicit way to convert from other types (e.g. numbers) into booleans. So unless the variable that is assigned to has type boolean (or wrapper type Boolean), there will be a compile error.
In Ada and Python
, assignment operators cannot appear in an expression
(including
, will provide a warning when compiling code that contains an assignment operator inside an if statement, though there are some legitimate uses of an assignment inside an if-condition. In those cases the programmer would need to explicitly wrap the assignment in an extra pair of parentheses to avoid the warning.
Similarly, some languages, such as BASIC
use just the "
Some programmers get in the habit of writing comparisons against a constant in the reverse of the usual order:
If the programmer accidentally uses
. In such languages, there becomes a need to test for two different types of equality:
The first type of equality usually implies the second (except for things like NaN
which are unequal to themselves), but the converse is not necessarily true. For example, two string
objects may be distinct objects (unequal in the first sense) but contain the same sequence of characters (equal in the second sense). See identity
for more of this issue.
The following table lists the different mechanisms to test for these two types of equality in various languages:
The operator
The languages JavaScript
and PHP
extends this syntax, with the "
logical operators XOR, AND, OR, and NOT, relational operators can be designed to have logical equivalence
, such that they can all be defined in terms of one another. The following four conditional statements all have the same logical equivalence:
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...
, a relational operator is a programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
construct or operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...
that tests or defines some kind of relation
Relation (mathematics)
In set theory and logic, a relation is a property that assigns truth values to k-tuples of individuals. Typically, the property describes a possible connection between the components of a k-tuple...
between two entities
Binary function
In mathematics, a binary function, or function of two variables, is a function which takes two inputs.Precisely stated, a function f is binary if there exists sets X, Y, Z such that\,f \colon X \times Y \rightarrow Z...
. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 ≥ 3). In programming languages that include a distinct boolean data type in their type system
Type system
A type system associates a type with each computed value. By examining the flow of these values, a type system attempts to ensure or prove that no type errors can occur...
, like Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, these operators return true or false, depending on whether the conditional relationship between the two operands holds or not. In other languages such as C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, relational operators return the integers 0 or 1.
An expression
Expression (programming)
An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
created using a relational operator forms what is known as a relational expression or a condition. Relational operators are also used in technical literature instead of words. Relational operators are usually written in infix notation
Infix notation
Infix notation is the common arithmetic and logical formula notation, in which operators are written infix-style between the operands they act on . It is not as simple to parse by computers as prefix notation or postfix notation Infix notation is the common arithmetic and logical formula 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 C will print the message if the x is less than y:
Other programming languages, such as Lisp, use prefix notation, as follows:
Standard relational operators
The most common numerical relational operators used in programming languages are shown below.Other conventions are less common: Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...
and Macsyma
Macsyma
Macsyma is a computer algebra system that was originally developed from 1968 to 1982 at MIT as part of Project MAC and later marketed commercially...
/Maxima use Basic-like operators except for inequality, which is /= in Common Lisp and # in Macsyma/Maxima. Older Lisp
Lisp
A lisp is a speech impediment, historically also known as sigmatism. Stereotypically, people with a lisp are unable to pronounce sibilants , and replace them with interdentals , though there are actually several kinds of lisp...
s used
equal
, greaterp
, and lessp
; and negated them using not
for the remaining operators.Confusion with assignment operators
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 and ALGOL (1958 and 1960) therefore introduced "
:=
" for assignment, leaving the standard "=
" available for equality, a convention followed by CPLCPL
-In business:* Cost per Lead, associated with the Pay per Lead Marketing method* NYSE stock symbol of CPFL Energia* Irish resourcing company CPL Resources Pld...
, Algol W
ALGOL W
ALGOL W is a programming language. It was based on a proposal for ALGOL X by Niklaus Wirth and C. A. R. Hoare as a successor to ALGOL 60 in IFIP Working Group 2.1. When the committee decided that the proposal was not a sufficient advance over ALGOL 60, the proposal was published as A contribution...
, BCPL
BCPL
BCPL is a procedural, imperative, and structured computer programming language designed by Martin Richards of the University of Cambridge in 1966.- Design :...
, Simula
Simula
Simula is a name for two programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard...
, Algol 68
ALGOL 68
ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...
, SETL
SETL
SETL is a very-high level programming language based on the mathematical theory of sets. It was originally developed by Jack Schwartz at the NYU Courant Institute of Mathematical Sciences in the late 1960s....
, Pascal
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
, Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, Modula2, Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
, Standard ML
Standard ML
Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML...
, Objective Caml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...
, Eiffel
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...
, Delphi
Object Pascal
Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...
, Oberon
Oberon
Oberon is a legendary king of the fairies.Oberon may also refer to:-People:* Merle Oberon , British actress* Oberon Zell-Ravenheart , Neopagan activist-Media and entertainment:* Oberon...
, Dylan, VHDL, and several other languages.
On the other hand, the now very influential language C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
started off as a minimal compiled language called B, which, in turn, started off as a simplified version of BCPL
BCPL
BCPL is a procedural, imperative, and structured computer programming language designed by Martin Richards of the University of Cambridge in 1966.- Design :...
(a typeless version of CPL
CPL
-In business:* Cost per Lead, associated with the Pay per Lead Marketing method* NYSE stock symbol of CPFL Energia* Irish resourcing company CPL Resources Pld...
). The intented application for B was solely as a vehicle for a first port of (a then very primitive) UNIX. In what that has been described as a "strip-down" process, B replaced the original "
:=
" and "=
" of BCPL by "=
" and "
" respectively, the reason for this being unknown (and and or meanwhile became "&" and "|", and later "&&" and "||", respectively). As a small type system was later introduced, B became C. The popularity of C, and its association with UNIX, led to Java, C#, and other languages (including new versions of Fortran) following suit, syntactically, despite this unnecessary conflict with the mathematical meaning of the equal sign.Languages
Assignments in C have a value and since any non-zero scalar value is interpreted as true in conditional expressions, the code "if (x = y)
" is legal, but has a very different meaning from "if (x y)
". The former code fragment means "assign y to x, and if the new value of x is not zero, execute the following statement". The latter fragment means "if and only ifIf and only if
In logic and related fields such as mathematics and philosophy, if and only if is a biconditional logical connective between statements....
x is equal to y, execute the following statement".
Though Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
and C# have the same operators as C, this mistake usually causes a compile error in these languages instead, because the if-condition must be of type boolean, and there is no implicit way to convert from other types (e.g. numbers) into booleans. So unless the variable that is assigned to has type boolean (or wrapper type Boolean), there will be a compile error.
In Ada and Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, assignment operators cannot appear in an expression
Expression (programming)
An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
(including
if
clauses), thus precluding this class of error. Some compilers, such as GCCGNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
, will provide a warning when compiling code that contains an assignment operator inside an if statement, though there are some legitimate uses of an assignment inside an if-condition. In those cases the programmer would need to explicitly wrap the assignment in an extra pair of parentheses to avoid the warning.
Similarly, some languages, such as BASIC
BASIC
BASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....
use just the "
=
" symbol for both assignment and equality, as they are syntactically separate (as with Ada and Python, 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 the programmer accidentally uses
=
, the resulting code is invalid because 2 is not a variable. The compiler will generate an error message, upon which the proper operator can be substituted. This coding style is known as left-hand comparison.Object identity vs. Content equality
In many modern programming languages, objects and data structures are accessed through referencesReference (computer science)
In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...
. In such languages, there becomes a need to test for two different types of equality:
- Physical (or shallow) equality - whether two references reference the same object.
- Structural (or deep) equality - whether the objects referenced by two references are equivalent in some sense (e.g. their contents are the same).
The first type of equality usually implies the second (except for things like NaN
NaN
In computing, NaN is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations...
which are unequal to themselves), but the converse is not necessarily true. For example, two string
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....
objects may be distinct objects (unequal in the first sense) but contain the same sequence of characters (equal in the second sense). See identity
Identity (object-oriented programming)
An identity in object-oriented programming, object-oriented design and object-oriented analysis describes the property of objects that distinguishes them from other objects. This is closely related to the philosophical concept of identity....
for more of this issue.
The following table lists the different mechanisms to test for these two types of equality in various languages:
Language | Physical equality | Structural equality | Notes |
---|---|---|---|
ALGOL 68 ALGOL 68 ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a... |
a :=: b or a is b |
a = b |
when a and b are pointers |
C C (programming language) C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.... , C++ C++ C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell... |
a |
*a *b |
when a and b are pointers |
C# | object.ReferenceEquals(a, b) |
a.Equals(b) |
The operator defaults to ReferenceEquals , but can be overloadedOperator overloading In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments... to perform Equals instead. |
Common Lisp Common Lisp Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers... |
(eq a b) |
(equal a b) |
|
Go Go (programming language) Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being... |
a b |
reflect.DeepEqual(*a, *b) |
when a and b are pointers |
Java Java (programming language) Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities... |
a |
a.equals(b) |
|
Objective Caml Objective Caml OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996... , Smalltalk Smalltalk Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist... |
a b |
a = b |
|
Pascal Pascal (programming language) Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal... |
a^ = b^ |
a = b |
|
Perl Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular... |
$a |
$$a $$b |
when $a and $b are references to scalars |
PHP PHP PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document... 5 |
$a $b |
$a |
when $a and $b are objects |
Python Python (programming language) Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive... |
a is b |
a b |
|
Ruby Ruby (programming language) Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto... |
a.equal?(b) |
a b |
|
Scheme | (eq? a b) |
(equal? a b) |
|
Visual Basic .NET Visual Basic .NET Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework... Patent application: On 14 May 2003, "IS NOT OPERATOR" was filed for the ISNOT operator by employees of MicrosoftMicrosoft Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions... . This patent was granted on 18 November 2004. |
a Is b |
a = b |
|
Objective-C Objective-C Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it... |
a b |
[a isEqual:b] |
when a and b are pointers to objects that are instances of NSObject |
The
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
and PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
extends this syntax, with the "
" operator able to return true if two values are equal, even if they have different types (for example, "4 "4"
" is true), and the "
" operator returning true only if two values are equal and have equivalent types as well (such that "4 "4"
" is false but "4 4
" is true). This comes in handy when checking if a value is assigned the value of 0, since "x 0
" is true for x being 0
, but also for x being "0"
(i.e. a string containing the character 0) and false
(as PHP, like other languages, equates 0
to false
), and that is not always what one wants, but "x 0
" is only true when x is 0
. When comparing objects in PHP 5, the "
" operator tests for structural equality, while the "
" operator tests for physical equality.Logical equivalence
Though perhaps not obvious at first, like the booleanBoolean logic
Boolean algebra is a logical calculus of truth values, developed by George Boole in the 1840s. It resembles the algebra of real numbers, but with the numeric operations of multiplication xy, addition x + y, and negation −x replaced by the respective logical operations of...
logical operators XOR, AND, OR, and NOT, relational operators can be designed to have logical equivalence
Logical equivalence
In logic, statements p and q are logically equivalent if they have the same logical content.Syntactically, p and q are equivalent if each can be proved from the other...
, such that they can all be defined in terms of one another. The following four conditional statements all have the same logical equivalence:
See also
- Binary relationBinary relationIn mathematics, a binary relation on a set A is a collection of ordered pairs of elements of A. In other words, it is a subset of the Cartesian product A2 = . More generally, a binary relation between two sets A and B is a subset of...
- Common operator notationCommon operator notationIn programming languages, common operator notation is one way of notating mathematical expressions as a linear sequence of tokens, or operators.In this model, tokens are divided into two classes: operators and operands....
- Equality (mathematics)
- Equals signEquals signThe equality sign, equals sign, or "=" is a mathematical symbol used to indicate equality. It was invented in 1557 by Robert Recorde. The equals sign is placed between the things stated to have the same value, as in an equation...
- Logical operator
- Operation (mathematics)Operation (mathematics)The general operation as explained on this page should not be confused with the more specific operators on vector spaces. For a notion in elementary mathematics, see arithmetic operation....
- Operator (mathematics)
- Operator (programming)Operator (programming)Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...
- Spaceship operatorSpaceship operatorThe spaceship operator, written , is a binary relational operator that originated in the Perl programming language. Other languages, such as Ruby and Groovy also support the spaceship operator...
- Triadic relationTriadic relationIn mathematics, a ternary relation or triadic relation is a finitary relation in which the number of places in the relation is three. Ternary relations may also be referred to as 3-adic, 3-ary, 3-dimensional, or 3-place....