Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When comparing for equality is it okay to use `==`?

Tags:

c++

equality

When comparing for equality is it okay to use ==?

For example:

int a = 3;
int b = 4;

If checking for equality should you use:

if (a == b)
{
     . . .
}

Would the situation change if floating point numbers were used?

like image 398
Brandon Tiqui Avatar asked Feb 11 '10 06:02

Brandon Tiqui


People also ask

Should I use == or ===?

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false . Both are equally quick. The lack of transitivity is alarming.

How do you use comparatives of equality?

Comparison of equality (as…as) When you want to express that two nouns are equal, it is possible to use the following comparative form “as + adjective/adverb + as". It is a way comparing two nouns in an equal way.

What is an equality comparison?

To summarize comparison of equality is used to show that two things, people are similar. There is no difference between the subject and the object. It can be used with adjectives, adverbs and nouns.

Is there any difference between == and === in a comparison?

= is used for assigning values to a variable, == is used for comparing two variables, but it ignores the datatype of variable whereas === is used for comparing two variables, but this operator also checks datatype and compares two values.

What does == mean?

The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

When would you use == vs equal () and what is the difference?

The main difference between the . equals() method and == operator is that one is a method, and the other is the operator. We can use == operators for reference comparison (address comparison) and . equals() method for content comparison.


2 Answers

'==' is perfectly good for integer values.

You should not compare floats for equality; use an tolerance approach:

if (fabs(a - b) < tolerance)
{
   // a and b are equal to within tolerance
}
like image 137
Mitch Wheat Avatar answered Oct 05 '22 23:10

Mitch Wheat


Re floating points: yes. Don't use == for floats (or know EXACTLY what you're doing if you do). Rather use something like

if (fabs(a - b) < SOME_DELTA) {
  ...
}

EDIT: changed abs() to fabs()

like image 21
Frank Shearar Avatar answered Oct 06 '22 00:10

Frank Shearar