==
From Wikipedia, the free encyclopedia
In many computer programming languages == is a boolean logic binary relation representing equality. An example usage may be "x == y", which will return "true" if x is equal to y and "false" if it is not.[1]
[edit] Use
Thus the below piece of code, using an if statement will print "x is equal to y" if x is equal to (holds the same value as) y and will print "x is not equal to y" if x is not equal to y.
if (x == y) { printf("x is equal to y\n"); } else { printf("x is not equal to y\n"); }
In languages that use "==" to test for equality, the "==" operator is distinct from the "=" operator, the latter being used for assignment. Languages that use this style include all C-style languages, such as C, Java, and PHP.
[edit] Pitfalls
The similarity in appearance between "==" and "=" in these languages can lead to coding errors. A programmer may mistype "if (x = y)", having intended "if (x == y)". In C, the former code fragment roughly means "assign y to x, and if the new value of x is not zero, execute the statement following". The latter code fragment roughly means "if and only if x is equal to y, execute the statement following". For example, the following code should print "x is 2 and y is 2" because "if (x = y)" assigns y to x, making both equal to 2, and then executes the following code because 2 is not zero.[1]
int x = 1; int y = 2; if (x = y) { /* This code will always execute */ printf("x is %d and y is %d\n", x, y); }
For this reason, many non-C style languages, such as Eiffel, Pascal and Ada use "=" for equality testing and ":=" for assignment. These two syntactic elements are more easily distinguishable, and thus it is easier to spot situations where an assignment has been used mistakenly in place of an equality test. It is also harder to mistype =
as :=
.
In Ada and Python assignment operator cannot appear in an expression (including if
clauses), thus precluding this class of error. Some compilers, such as GCC, will provide a warning when compiling code that contains an assignment operator inside an if statement.
Some programmers also write comparisons in the reverse of the usual order, as in 2 == a
. 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.