https://gcc.gnu.org/g:a7f188ccaf721ab04f569a6c140dd1b1c73ab500

commit r16-5137-ga7f188ccaf721ab04f569a6c140dd1b1c73ab500
Author: Alejandro Colomar <[email protected]>
Date:   Mon Nov 10 19:26:21 2025 +0000

    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 <[email protected]>
    Suggested-by: Andrew Pinski <[email protected]>
    Signed-off-by: Alejandro Colomar <[email protected]>

Diff:
---
 gcc/c-family/c-common.cc               | 8 +++++++-
 gcc/testsuite/gcc.dg/countof-compile.c | 6 ++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/gcc/c-family/c-common.cc b/gcc/c-family/c-common.cc
index 1c382540b38a..9b97a0fe6224 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 afd5659618b4..ebbac16ed38d 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);
+}

Reply via email to