From: Alejandro Colomar Date: Mon, 10 Nov 2025 19:26:21 +0000 (+0000) Subject: c: Fix return type of _Countof [PR122591] X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=a7f188ccaf721ab04f569a6c140dd1b1c73ab500;p=thirdparty%2Fgcc.git c: Fix return type of _Countof [PR122591] PR c/122591 gcc/c-family/ChangeLog: * c-common.cc (c_countof_type): Convert return value to size_t. gcc/testsuite/ChangeLog: * gcc.dg/countof-compile.c (type): Test return type of _Countof. Reported-by: Sam James Suggested-by: Andrew Pinski Signed-off-by: Alejandro Colomar --- diff --git a/gcc/c-family/c-common.cc b/gcc/c-family/c-common.cc index 1c382540b38..9b97a0fe622 100644 --- a/gcc/c-family/c-common.cc +++ b/gcc/c-family/c-common.cc @@ -4114,6 +4114,7 @@ tree c_countof_type (location_t loc, tree type) { enum tree_code type_code; + tree value; type_code = TREE_CODE (type); if (type_code != ARRAY_TYPE) @@ -4129,7 +4130,12 @@ c_countof_type (location_t loc, tree type) return error_mark_node; } - return array_type_nelts_top (type); + value = array_type_nelts_top (type); + /* VALUE will have the middle-end integer type sizetype. + However, we should really return a value of type `size_t', + which is just a typedef for an ordinary integer type. */ + value = fold_convert_loc (loc, size_type_node, value); + return value; } /* Handle C and C++ default attributes. */ diff --git a/gcc/testsuite/gcc.dg/countof-compile.c b/gcc/testsuite/gcc.dg/countof-compile.c index afd5659618b..ebbac16ed38 100644 --- a/gcc/testsuite/gcc.dg/countof-compile.c +++ b/gcc/testsuite/gcc.dg/countof-compile.c @@ -122,3 +122,9 @@ const_expr(void) _Static_assert (_Countof (int [3][n]) == 3); _Static_assert (_Countof (int [n][3]) == 7); /* { dg-error "not constant" } */ } + +void +type(void) +{ + _Generic (_Countof (w), __typeof__ (sizeof 0): 0); +}