[Bug c++/91335] False positive "unused variable" warning with variable initialized in 'if' condition
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91335 Martin Sebor changed: What|Removed |Added Status|UNCONFIRMED |RESOLVED CC||msebor at gcc dot gnu.org Resolution|--- |INVALID --- Comment #5 from Martin Sebor --- Declaring the variable with attribute unused (or [[maybe_unused]]) is the intended mechanism to suppress the warning when the variable is meant to be declared but not otherwise referenced: int main() { if (int *f __attribute__ ((unused)) = foo()) return 1; } I agree that the warning for the test case is not just by design but desirable, and since there are several straightforward solutions I think this report should be resolved invalid.
[Bug c++/91335] False positive "unused variable" warning with variable initialized in 'if' condition
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91335 --- Comment #4 from Andreas Schwab --- Or add a conversion to bool that does the right thing?
[Bug c++/91335] False positive "unused variable" warning with variable initialized in 'if' condition
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91335 --- Comment #3 from Jonathan Wakely --- You can still do that without a named variable: if (static_cast(foo())) { return 1; }
[Bug c++/91335] False positive "unused variable" warning with variable initialized in 'if' condition
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91335 --- Comment #2 from Nathan Ridge --- I suppose a fair question here is, if I'm not going to use 'f', why don't I just write: if (foo()) { return 1; } ? That would certainly work in this case. However, in the original code example that motivated this report, foo() returned a class type which had a templated conversion operator, and it's the result of that conversion operator (instantiated with a pointer type) that I wanted to test. In such a case, I need the declaration form to trigger invoking the conversion operator.
[Bug c++/91335] False positive "unused variable" warning with variable initialized in 'if' condition
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91335 --- Comment #1 from Nathan Ridge --- (In reply to Nathan Ridge from comment #0) > As a result, the only way to fix the warning is to lift the variable into > the outer scope, which can be undesirable from a code style point of view: (Well, or I could add a "(void) f;" statement in the if body. Equally undesirable.)