You can use memset
, but only because our selection of types is restricted to integral types.
In general case in C it makes sense to implement a macro
#define ZERO_ANY(T, a, n) do{\
T *a_ = (a);\
size_t n_ = (n);\
for (; n_ > 0; --n_, ++a_)\
*a_ = (T) { 0 };\
} while (0)
This will give you C++-like functionality that will let you to "reset to zeros" an array of objects of any type without having to resort to hacks like memset
. Basically, this is a C analog of C++ function template, except that you have to specify the type argument explicitly.
On top of that you can build a "template" for non-decayed arrays
#define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a))
#define ZERO_ANY_A(T, a) ZERO_ANY(T, (a), ARRAY_SIZE(a))
In your example it would be applied as
int a[100];
ZERO_ANY(int, a, 100);
// or
ZERO_ANY_A(int, a);
It is also worth noting that specifically for objects of scalar types one can implement a type-independent macro
#define ZERO(a, n) do{\
size_t i_ = 0, n_ = (n);\
for (; i_ < n_; ++i_)\
(a)[i_] = 0;\
} while (0)
and
#define ZERO_A(a) ZERO((a), ARRAY_SIZE(a))
turning the above example into
int a[100];
ZERO(a, 100);
// or
ZERO_A(a);