Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for countof() to test if its argument is an array?

Tags:

arrays

c

A classic macro to compute the number of elements in an array is this:

#define countof(a)  (sizeof(a) / sizeof(*(a)))

The problem with this is it fails silently if the argument is a pointer instead of an array. Is there a portable way to ensure this macro is only used with an actual array by generating a compile time error if a is not an array?

EDIT: my question seems to be a duplicate of this one: Array-size macro that rejects pointers

like image 378
chqrlie Avatar asked Jun 19 '17 02:06

chqrlie


People also ask

How do you count the occurrences of a particular element in an array?

To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .

How do you find the number of elements in an array in C++?

Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof() . int numArrElements = sizeof(myArray) / sizeof(int);


1 Answers

Using a non-portable built-in function, here is a macro to perform a static assertion that a is an array:

#define assert_array(a) \
     (sizeof(char[1 - 2 * __builtin_types_compatible_p(typeof(a), typeof(&(a)[0]))]) - 1)

It works with both gcc and clang. I use it to make the countof() macro safer:

#define countof(a)  (sizeof(a) / sizeof(*(a)) + assert_array(a))

But I don't have a portable solution for this problem.

like image 137
chqrlie Avatar answered Oct 03 '22 14:10

chqrlie