]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
c: Fix return type of _Countof [PR122591]
authorAlejandro Colomar <alx@kernel.org>
Mon, 10 Nov 2025 19:26:21 +0000 (19:26 +0000)
committerJoseph Myers <josmyers@redhat.com>
Mon, 10 Nov 2025 19:27:25 +0000 (19:27 +0000)
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 <sam@gentoo.org>
Suggested-by: Andrew Pinski <andrew.pinski@oss.qualcomm.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
gcc/c-family/c-common.cc
gcc/testsuite/gcc.dg/countof-compile.c

index 1c382540b38a5c54b0a87fd60e6fe21d18f31874..9b97a0fe62243f476bc7d3a46bae46ecd889c3b2 100644 (file)
@@ -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;
 }
 \f
 /* Handle C and C++ default attributes.  */
index afd5659618b4505b15d790ef371b84bb0d3c5c3f..ebbac16ed38d19dd44dcab5ec9a9fe3033fe345c 100644 (file)
@@ -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);
+}