[PATCH] D152495: [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

Aaron Ballman via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Fri Jul 7 11:51:18 PDT 2023


aaron.ballman added a comment.

This is a bit of an odd situation -- the condition variable *is* used (e.g., its value is loaded to determine whether to go into the if branch or the else branch), so we should not be marking it as unused in `Sema::CheckConditionVariable()`. Instead, I think we need to decide what constitutes "unused" in this case. Consider:

  struct RAII {
    int &x;
  
    RAII(int &ref) : x(ref) {}
    ~RAII() { x = 0; }
  
    operator bool() const { return true; }
  };
  
  void func() {
    int i = 12;
    if (RAII name{i}) {
    }
  }

I don't think `name` is unused in the same way that `i` is unused in `if (int i = 1) {}`. So I think we only want this to apply to scalars and not class types. I think the changes should be happening in `Sema::ShouldDiagnoseUnusedDecl()`  (and you might need to thread the `Scope` object through to that call -- my naive thinking is that a variable declaration in a condition scope should be diagnosed as unused if it is used but not referenced, but I could be off-base).



================
Comment at: clang/docs/ReleaseNotes.rst:340
   with ``__attribute__((cleanup(...)))`` to match GCC's behavior.
+- Clang now warns on unused variables declaread and initialized in condition
+  expressions.
----------------



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152495/new/

https://reviews.llvm.org/D152495



More information about the cfe-commits mailing list