[PATCH] D15814: Implicit conversion from float->bool

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 29 13:14:49 PST 2015


aaron.ballman created this revision.
aaron.ballman added reviewers: rsmith, rtrieu, dblaikie.
aaron.ballman added a subscriber: cfe-commits.

When performing an implicit from float to bool, the floating point value must be *exactly* zero in order for the conversion to result in 0. This does not involve a conversion through an integer value, and so truncation of the value is not performed. This patch addresses this by using the floating-point value when determining whether to print "true" or "false" in the diagnostic. The behavior of the codegen has always been correct, so this only modifies the wording of the diagnostic to be accurate.

This patch address PR25876.

http://reviews.llvm.org/D15814

Files:
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/warn-literal-conversion.cpp

Index: test/SemaCXX/warn-literal-conversion.cpp
===================================================================
--- test/SemaCXX/warn-literal-conversion.cpp
+++ test/SemaCXX/warn-literal-conversion.cpp
@@ -38,3 +38,14 @@
   int y = (24*60*60) * 0.25;
   int pennies = 123.45 * 100;
 }
+
+// Similarly, test floating point conversion to bool. Only float values of zero
+// are converted to false; everything else is converted to true.
+void test1() {
+  bool b1 = 0.99f; // expected-warning {{implicit conversion from 'float' to 'bool' changes value from 0.99 to true}}
+  bool b2 = 0.99; // expected-warning {{implicit conversion from 'double' to 'bool' changes value from 0.99 to true}}
+  // These do not warn because they can be directly converted to integral
+  // values.
+  bool b3 = 0.0f;
+  bool b4 = 0.0;
+}
Index: lib/Sema/SemaChecking.cpp
===================================================================
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -6983,7 +6983,7 @@
 
   SmallString<16> PrettyTargetValue;
   if (T->isSpecificBuiltinType(BuiltinType::Bool))
-    PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
+    PrettyTargetValue = Value.isZero() ? "false" : "true";
   else
     IntegerValue.toString(PrettyTargetValue);
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D15814.43757.patch
Type: text/x-patch
Size: 1276 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20151229/b7320068/attachment.bin>


More information about the cfe-commits mailing list