xref: /llvm-project/clang/test/Sema/floating-point-compare.c (revision ab982eace6e4951a2986567d29f4d6be002c1ba7)
1 // RUN: %clang_cc1 -fsyntax-only -Wfloat-equal -verify %s
2 
f1(float x,float y)3 int f1(float x, float y) {
4   return x == y; // expected-warning {{comparing floating point with ==}}
5 }
6 
f2(float x,float y)7 int f2(float x, float y) {
8   return x != y; // expected-warning {{comparing floating point with ==}}
9 }
10 
f3(float x)11 int f3(float x) {
12   return x == x; // no-warning
13 }
14 
15 // 0.0 can be represented exactly, so don't warn.
f4(float x)16 int f4(float x) {
17   return x == 0.0; // no-warning {{comparing}}
18 }
19 
f5(float x)20 int f5(float x) {
21   return x == __builtin_inf(); // no-warning
22 }
23 
24 // The literal is a double that can't be represented losslessly as a float.
tautological_FP_compare(float x)25 int tautological_FP_compare(float x) {
26   return x == 3.14159; // expected-warning {{floating-point comparison is always false}}
27 }
28 
tautological_FP_compare_inverse(float x)29 int tautological_FP_compare_inverse(float x) {
30   return x != 3.14159; // expected-warning {{floating-point comparison is always true}}
31 }
32 
33 // The literal is a double that can be represented losslessly as a long double,
34 // but this might not be the comparison what was intended.
not_tautological_FP_compare(long double f)35 int not_tautological_FP_compare(long double f) {
36   return f == 0.1; // expected-warning {{comparing floating point with ==}}
37 }
38 
tautological_FP_compare_commute(float f)39 int tautological_FP_compare_commute(float f) {
40   return 0.3 == f; // expected-warning {{floating-point comparison is always false}}
41 }
42 
tautological_FP_compare_commute_inverse(float f)43 int tautological_FP_compare_commute_inverse(float f) {
44   return 0.3 != f; // expected-warning {{floating-point comparison is always true}}
45 }
46 
tautological_FP_compare_explicit_upcast(float f)47 int tautological_FP_compare_explicit_upcast(float f) {
48   return 0.3 == (double) f; // expected-warning {{floating-point comparison is always false}}
49 }
50 
tautological_FP_compare_explicit_downcast(double d)51 int tautological_FP_compare_explicit_downcast(double d) {
52   return 0.3 == (float) d; // expected-warning {{floating-point comparison is always false}}
53 }
54 
tautological_FP_compare_ignore_parens(float f)55 int tautological_FP_compare_ignore_parens(float f) {
56   return f == (0.3); // expected-warning {{floating-point comparison is always false}}
57 }
58 
59 #define CST 0.3
60 
tautological_FP_compare_macro(float f)61 int tautological_FP_compare_macro(float f) {
62   return f == CST; // expected-warning {{floating-point comparison is always false}}
63 }
64