From: Martin Uecker Date: Tue, 12 May 2026 05:11:38 +0000 (+0200) Subject: c: avoid false positive for useless casts and generic [PR125261] X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=dee30fc0e980ee26a804a74da74decc0cea10b8f;p=thirdparty%2Fgcc.git c: avoid false positive for useless casts and generic [PR125261] To reduce the number of false positives, we guard -Wuseless-cast by c_inhibit_evaluation_warnings and also increment it for a generic association if we have seen a prior match for a (non-default) association. This covers the common case where the default association comes last. If there is another association selected after we have seen a default, we still have false positives. PR c/125261 gcc/c/ChangeLog: * c-parser.cc (c_parser_generic_selection): Modify logic for c_inhibit_evaluation_warnings. * c-typeck.cc (build_c_cast): Use c_inhibit_evaluation_warnings. gcc/testsuite/ChangeLog: * gcc.dg/pr125261.c: New test. --- diff --git a/gcc/c/c-parser.cc b/gcc/c/c-parser.cc index 9ddb449d710..daf57061ee9 100644 --- a/gcc/c/c-parser.cc +++ b/gcc/c/c-parser.cc @@ -11469,14 +11469,14 @@ c_parser_generic_selection (c_parser *parser) bool match = assoc.type == NULL_TREE || comptypes (assoc.type, selector_type); - if (!match) + if (!match || matched_assoc.type != NULL_TREE) c_inhibit_evaluation_warnings++; in_generic++; assoc.expression = c_parser_expr_no_commas (parser, NULL); - if (!match) - c_inhibit_evaluation_warnings--; + if (!match || matched_assoc.type != NULL_TREE) + c_inhibit_evaluation_warnings--; in_generic--; if (!match) pop_maybe_used (!flag_isoc23); diff --git a/gcc/c/c-typeck.cc b/gcc/c/c-typeck.cc index 6195d179543..a03ec920e19 100644 --- a/gcc/c/c-typeck.cc +++ b/gcc/c/c-typeck.cc @@ -7417,7 +7417,7 @@ build_c_cast (location_t loc, tree type, tree expr) && pedwarn (loc, OPT_Wpedantic, "ISO C forbids casting nonscalar to the same type")) ; - else if (warn_useless_cast) + else if (warn_useless_cast && c_inhibit_evaluation_warnings == 0) warning_at (loc, OPT_Wuseless_cast, "useless cast to type %qT", type); diff --git a/gcc/testsuite/gcc.dg/pr125261.c b/gcc/testsuite/gcc.dg/pr125261.c new file mode 100644 index 00000000000..1bac78a82c2 --- /dev/null +++ b/gcc/testsuite/gcc.dg/pr125261.c @@ -0,0 +1,12 @@ +/* { dg-do compile } */ +/* { dg-options "-Wuseless-cast" } */ + + +static int i = _Generic(0., int: (int)0, default: 0); +static int j = _Generic(0, int: 0, default: (int)0, float: 0); +static int k = _Generic(0, default: 0, int: (int)0); /* { dg-warning "useless" } */ + +/* If the active assocation cames later than the default, we do + not know that it is unused. */ +// static int l = _Generic(0, default: (int)0, int: 0); +