lmi-commits
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[lmi-commits] [lmi] master 4f2f4bf7 05/13: Avoid gratuitous UB


From: Greg Chicares
Subject: [lmi-commits] [lmi] master 4f2f4bf7 05/13: Avoid gratuitous UB
Date: Fri, 10 Jun 2022 21:09:37 -0400 (EDT)

branch: master
commit 4f2f4bf7e7316fdbfcde7d75af6a42ad8ef67acc
Author: Gregory W. Chicares <gchicares@sbcglobal.net>
Commit: Gregory W. Chicares <gchicares@sbcglobal.net>

    Avoid gratuitous UB
    
    Floating-point division by zero is well defined by IEEE 754, yet is UB
    even when std::numeric_limits<T>::is_iec559 is 'true' (and even when
    __STDC_IEC_559__ is defined). It can be argued that the C++ standard
    should instead make it implementation-defined, at least when IEC 559
    conformance is promised. However, division by zero should be avoided
    where easily possible, as here.
---
 duff_fmt_test.cpp | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/duff_fmt_test.cpp b/duff_fmt_test.cpp
index cae0e024..07e647f1 100644
--- a/duff_fmt_test.cpp
+++ b/duff_fmt_test.cpp
@@ -230,19 +230,19 @@ int test_main(int, char*[])
 
     // Infinities and NaNs.
 
-    double volatile d = 0.0;
-    std::string pos_inf = duff_fmt( 1.0 / d, 2);
-    std::string neg_inf = duff_fmt(-1.0 / d, 2);
-    LMI_TEST( "inf" == pos_inf ||  "infinity" == pos_inf);
-    LMI_TEST("-inf" == neg_inf || "-infinity" == neg_inf);
+    constexpr double inf {std::numeric_limits<double>::infinity()};
+    std::string str_pos_inf = duff_fmt( inf, 2);
+    std::string str_neg_inf = duff_fmt(-inf, 2);
+    LMI_TEST( "inf" == str_pos_inf ||  "infinity" == str_pos_inf);
+    LMI_TEST("-inf" == str_neg_inf || "-infinity" == str_neg_inf);
 
     if(std::numeric_limits<double>::has_quiet_NaN)
         {
-        constexpr double quiet_NaN = std::numeric_limits<double>::quiet_NaN();
-        std::string qnan = duff_fmt(quiet_NaN, 2);
+        constexpr double qnan {std::numeric_limits<double>::quiet_NaN()};
+        std::string str_nan = duff_fmt(qnan, 2);
         // Test only "nan", disregarding any 'n-char-sequence' payload.
         // The sign of quiet_NaN() seems to be unspecified.
-        LMI_TEST(begins_with(qnan, "nan") || begins_with(qnan, "-nan"));
+        LMI_TEST(begins_with(str_nan, "nan") || begins_with(str_nan, "-nan"));
         }
 
     return 0;



reply via email to

[Prev in Thread] Current Thread [Next in Thread]