1// RUN: %check_clang_tidy %s bugprone-assignment-in-if-condition %t
2
3void f(int arg) {
4 int f = 3;
5 if ((f = arg) || (f == (arg + 1)))
6 // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
7 {
8 f = 5;
9 }
10}
11
12void f1(int arg) {
13 int f = 3;
14 if ((f == arg) || (f = (arg + 1)))
15 // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
16 {
17 f = 5;
18 }
19}
20
21void f2(int arg) {
22 int f = 3;
23 if (f = arg)
24 // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
25 {
26 f = 5;
27 }
28}
29
30volatile int v = 32;
31
32void f3(int arg) {
33 int f = 3;
34 if ((f == arg) || ((arg + 6 < f) && (f = v)))
35 // CHECK-MESSAGES: :[[@LINE-1]]:42: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
36 {
37 f = 5;
38 }
39}
40
41void f4(int arg) {
42 int f = 3;
43 if ((f == arg) || ((arg + 6 < f) && ((f = v) || (f < 8))))
44 // CHECK-MESSAGES: :[[@LINE-1]]:43: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
45 {
46 f = 5;
47 } else if ((arg + 8 < f) && ((f = v) || (f < 8)))
48 // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
49 {
50 f = 6;
51 }
52}
53
54class BrokenOperator {
55public:
56 int d = 0;
57 int operator=(const int &val) {
58 d = val + 1;
59 return d;
60 }
61};
62
63void f5(int arg) {
64 BrokenOperator bo;
65 int f = 3;
66 bo = f;
67 if (bo.d == 3) {
68 f = 6;
69 }
70 if (bo = 3)
71 // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
72 {
73 f = 7;
74 }
75 if ((arg == 3) || (bo = 6))
76 // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: an assignment within an 'if' condition is bug-prone [bugprone-assignment-in-if-condition]
77 {
78 f = 8;
79 }
80 v = f;
81}
82
83// Tests that shouldn't trigger warnings.
84void awesome_f2(int arg) {
85 int f = 3;
86 if ((f == arg) || (f == (arg + 1))) {
87 f = 5;
88 }
89}
90
91void awesome_f3(int arg) {
92 int f = 3;
93 if (f == arg) {
94 f = 5;
95 }
96}
97
98void awesome_f4(int arg) {
99 int f = 3;
100 if ((f == arg) || ((arg + 6 < f) && ((f == v) || (f < 8)))) {
101 f = 5;
102 }
103}
104
105template <typename Func> bool exec(Func F) { return F(); }
106
107void lambda_if() {
108 int X;
109 if ([&X] {
110 X = 5;
111 return true;
112 }()) {
113 }
114
115 if (exec(F: [&] {
116 X = 5;
117 return true;
118 })) {
119 }
120}
121

source code of clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp