Agnel Kurian
Agnel Kurian

Reputation: 59476

Floating point constants in templated code

I have a template function operating on a floating point argument. The function is templated so that a caller can use either float, double or any other floating point data type.

At one point in my code, I compare a value with zero (or any other floating-point constant). Should I use 0.0 or 0.0f for the comparison?

template<T> void f(T a){
  //  should I use 0.0 or 0.0f in the following line?
  if(a == 0.0){
  }
}

While this is not causing any problems at the moment, I'd like to know what the usual practice is.

Upvotes: 8

Views: 289

Answers (3)

Simone
Simone

Reputation: 11797

You should not compare for equality on floating point number with a simple

if (value == 0.0) // or 0.0f, doesn't matter

because most of the time it won't yield the result you are expecting. You should check if value is enough close to the number you are expecting. That is:

if (abs(value - 0.0) < epsilon) 

where epsilon is something little enough for you application domain.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283733

I would suggest simply 0. According to the promotion rules for numeric types, 0 will get promoted to the type of the floating-point operand a. Promotion of a constant is a compile-time transformation, it won't slow your program down at all.


On the other hand, using 0.0 will force a run-time conversion of the other operand to double, which probably is a non-issue, as the operand is most likely passed in an FPU register anyway. 0.0f will not cause conversion of floating-point operands, but if the template was ever used with an integral type, you'd get run-time conversion to float.

Upvotes: 7

Alexandre C.
Alexandre C.

Reputation: 56976

I'd suggest

if (a == T(0)) ...

Upvotes: 13

Related Questions