Double divided by double and by integer: which one is better?

Viewed 109

I always assume that dividing a double by an integer will lead to faster code because the compiler will select the better microcode to compute:

double a;
double b = a/3.0;
double c = a/3; // will compute faster than b

For a single operation it does not matter, but for repetitive operations it can make difference. Is my assumption always correct or compiler or CPU dependent or whatever?

The same question applies for multiplication; i.e. will 3 * a be faster than 3.0 * a?

2 Answers

Your assumption is not correct because both your divide operations will be performed with two double operands. In the second case, c = a/3, the integer literal will be converted to a double value by the compiler before any code is generated.

From this Draft C++ Standard:

8.3 Usual arithmetic conversions          [expr.arith.conv]

1    Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

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


Note that, in this Draft C11 Standard, §6.3.1.8 (Usual arithmetic conversions) has equivalent (indeed, near-identical) text.

There is no difference. The integer operand is implicitly converted to a double, so they end up practically equivalent.

Related