2

In C++, are the following two comparisons different in any way?

double x = ...;
bool cmp1 = x > 1;
bool cmp2 = x > 1.0;

For cmp1, is the literal 1 converted to a double first like in usual mixed-type arithmetics? (If so, can you point me to the relevant definition in the standard?)

In general, does it matter if I compare/assign an integer literal or a floating-point literal to a floating-point variable? The assignment case looks like this:

double x1 = 1;
double x2 = 1.0;
Zizheng Tai
  • 6,170
  • 28
  • 79
  • [7.3.11-Floating-integral conversions](http://eel.is/c++draft/conv.fpint) See [7.3.1 - conv.general](http://eel.is/c++draft/conv.general) for all conversions. Inequality comparisons are generally okay, assignments are subject to truncation and whether an exact representation is possible. – David C. Rankin Mar 14 '21 at 04:34
  • See https://stackoverflow.com/q/5563000/5987. – Mark Ransom Mar 14 '21 at 04:35
  • They are the same. For binary operators see [expr.arith.conv/1.3](https://eel.is/c++draft/expr.arith.conv#1.3). For initializers see [dcl.init/15.9](https://eel.is/c++draft/dcl.init#general-15.9). For assignments see [expr.ass/3](https://eel.is/c++draft/expr.ass#3). – dxiv Mar 14 '21 at 04:39

1 Answers1

2

are the following two comparisons different in any way?

Usually no difference. They are the same. The RHS code becomes a double, then the compare occurs.


Below is C analysis which I am confident C++ inherits.

Potential differences come up when the source code value is inexact as a double (large integer).

With x > 12345678901234567891.0, the code is convert to a double per "the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner.

With x > 12345678901234567891u, the code is converted exactly to an integer constant and then to a double per "If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.

I would expect both of these to generate the same double, but given the slight wording difference and they are both implementation defined behavior, but not tied to each other, differences could exist. It comes down to the quality of implementation of the compiler.

Of course, source code integers outside the long long range are problematic.


In general, does it matter if I compare/assign an integer literal or a floating-point literal to a floating-point variable?

In general, best to compare by coding a common type. The path to forming the common type may expose subtle conversion effects.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256