Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing double to an int

While reading the book Programming Principles and Practice Using C++, in Chapter 3 it sates that we can;t directly compare a double to an int. However, when I tested it out on Visual Studios, it was running fine with no errors? What does he mean by not being able to compare double to an int. Later, he explains that C++ provides an indirect way. Does he mean implicit conversion?

like image 460
sangmin park Avatar asked Jan 28 '23 03:01

sangmin park


1 Answers

C++ has a sets of built-in operators defined in [over.built]. The behavior of the equality operator is defined in [expr.eq], in particular:

6 If both operands are of arithmetic or enumeration type, the usual arithmetic conversions are performed on both operands; each of the operators shall yield true if the specified relationship is true and false if it is false.

And usual arithmetic conversions implies:

(1.3) Otherwise, if either operand is double, the other shall be converted to double.

So if you compare an int with a float, a double or a long double, you get implicit conversions from int to float, double or long double.

like image 79
Holt Avatar answered Jan 30 '23 17:01

Holt