warn-dangling-else.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // RUN: %clang_cc1 -fsyntax-only -verify -Wdangling-else %s
  2. void f(int a, int b, int c, int d, int e) {
  3. // should warn
  4. { if (a) if (b) d++; else e++; } // expected-warning {{add explicit braces to avoid dangling else}}
  5. { if (a) while (b) if (c) d++; else e++; } // expected-warning {{add explicit braces to avoid dangling else}}
  6. { if (a) switch (b) if (c) d++; else e++; } // expected-warning {{add explicit braces to avoid dangling else}}
  7. { if (a) for (;;) if (c) d++; else e++; } // expected-warning {{add explicit braces to avoid dangling else}}
  8. { if (a) if (b) if (d) d++; else e++; else d--; } // expected-warning {{add explicit braces to avoid dangling else}}
  9. if (a)
  10. if (b) {
  11. d++;
  12. } else e++; // expected-warning {{add explicit braces to avoid dangling else}}
  13. // shouldn't
  14. { if (a) if (b) d++; }
  15. { if (a) if (b) if (c) d++; }
  16. { if (a) if (b) d++; else e++; else d--; }
  17. { if (a) if (b) if (d) d++; else e++; else d--; else e--; }
  18. { if (a) do if (b) d++; else e++; while (c); }
  19. if (a) {
  20. if (b) d++;
  21. else e++;
  22. }
  23. if (a) {
  24. if (b) d++;
  25. } else e++;
  26. }
  27. // Somewhat more elaborate case that shouldn't warn.
  28. class A {
  29. public:
  30. void operator<<(const char* s) {}
  31. };
  32. void HandleDisabledThing() {}
  33. A GetThing() { return A(); }
  34. #define FOO(X) \
  35. switch (0) default: \
  36. if (!(X)) \
  37. HandleDisabledThing(); \
  38. else \
  39. GetThing()
  40. void f(bool cond) {
  41. int x = 0;
  42. if (cond)
  43. FOO(x) << "hello"; // no warning
  44. }