xref: /llvm-project/clang/test/SemaCXX/warn-unused-but-set-variables-cpp.cpp (revision 90453f4a9a8955ac612959504941153aa376cb0c)
1 // RUN: %clang_cc1 -fblocks -fsyntax-only -Wunused-but-set-variable -verify %s
2 
3 struct S {
4   int i;
5 };
6 
7 struct __attribute__((warn_unused)) SWarnUnused {
8   int j;
9   void operator +=(int);
10   void operator ++();
11 };
12 
f0()13 int f0() {
14   int y; // expected-warning{{variable 'y' set but not used}}
15   y = 0;
16 
17   int z __attribute__((unused));
18   z = 0;
19 
20   // In C++, don't warn for structs. (following gcc's behavior)
21   struct S s;
22   struct S t;
23   s = t;
24 
25   // Unless it's marked with the warn_unused attribute.
26   struct SWarnUnused swu; // expected-warning{{variable 'swu' set but not used}}
27   struct SWarnUnused swu2;
28   swu = swu2;
29 
30   int x;
31   x = 0;
32   return x + 5;
33 }
34 
f1(void)35 void f1(void) {
36   (void)^() {
37     int y; // expected-warning{{variable 'y' set but not used}}
38     y = 0;
39 
40     int x;
41     x = 0;
42     return x;
43   };
44 }
45 
f2()46 void f2() {
47   // Don't warn for either of these cases.
48   constexpr int x = 2;
49   const int y = 1;
50   char a[x];
51   char b[y];
52 }
53 
f3(int n)54 void f3(int n) {
55   // Don't warn for overloaded compound assignment operators.
56   SWarnUnused swu;
57   swu += n;
58 }
59 
f4(T n)60 template<typename T> void f4(T n) {
61   // Don't warn for (potentially) overloaded compound assignment operators in
62   // template code.
63   SWarnUnused swu;
64   swu += n;
65 }
66 
f5()67 template <typename T> void f5() {
68   // Don't warn for overloaded pre/post operators in template code.
69   SWarnUnused swu;
70   ++swu;
71 }
72 
f6()73 void f6() {
74   if (int x = 123) {} // expected-warning{{variable 'x' set but not used}}
75 
76   while (int x = 123) {} // expected-warning{{variable 'x' set but not used}}
77 
78   for (; int x = 123;) {} // expected-warning{{variable 'x' set but not used}}
79 }
80