[clang] [Sema] Diagnose use of if/else-if condition variable inside else-if/else branch(s) (PR #156436)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Tue Oct 7 08:05:12 PDT 2025


AaronBallman wrote:

> Currently we can just "warn on common patterns that's bad sometimes", and that sounds something clang analyzer should do, rather than Sema.

Yeah, this is a tricky case because there are valid uses but it's also reasonably easy for there to be confused uses as well. We want to diagnose the confused uses without diagnosing the valid ones, and I'm not convinced that's possible to do with a heuristic. Even if it only applies to pointers, it will still diagnose valid uses, like:
```
if (int *ptr1 = get_something()) {
  return ptr1[0];
} else if (int *ptr2 = get_something_else()) {
  int x = 10;
  if (*ptr2 > 10)
    ptr1 = &x;     
  return foo(ptr1, ptr2) + x;
}
```
it might be perfectly fine for `foo` to accept either `nullptr` or a valid pointer, as done here. It's not how I'd write the code, but it is still valid code.

This might make more sense as a clang-tidy check.

https://github.com/llvm/llvm-project/pull/156436


More information about the cfe-commits mailing list