https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107913
Bug ID: 107913 Summary: Bogus unused variable warning if used in if constexpr false in lambda with default capture by ref Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: blubban at gmail dot com Target Milestone: --- template<bool a> int b() { constexpr int c = 123; constexpr int d = 456; return [&](){ if constexpr (a) return c; else return d; }(); } int g() { return b<true>(); } int h() { return b<false>(); } Compile with -Wall. Expected result: No warnings. Actual result: <source>: In instantiation of 'int b() [with bool a = true]': <source>:15:25: required from here <source>:5:19: warning: variable 'd' set but not used [-Wunused-but-set-variable] 5 | constexpr int d = 456; | ^ <source>: In instantiation of 'int b() [with bool a = false]': <source>:16:26: required from here <source>:4:19: warning: variable 'c' set but not used [-Wunused-but-set-variable] 4 | constexpr int c = 123; | ^ The warning is very fragile, and goes away if (pick one or more) - either variable is changed to not constexpr (oddly enough, both warnings disappear if either variable is not constexpr) - either variable is changed to static - the if is changed to not constexpr - the lambda is removed - the variables are captured explicitly - the lambda's default capture is by-value (The bug does reproduce if the template is removed and changed to if constexpr (true), but I feel the current form better demonstrates that the warning is inappropriate.) https://godbolt.org/z/T9nnzjj91