C is Brittle D is Plastic

Patrick Schluter Patrick.Schluter at bbox.fr
Thu Apr 2 17:37:18 UTC 2026


On Tuesday, 31 March 2026 at 19:39:20 UTC, Forum User wrote:
> On Monday, 30 March 2026 at 14:23:35 UTC, Dennis wrote:
>
>> ```C
>> #define ArrayCount(a) (sizeof(a) / sizeof((a)[0]))
>> ```

This construct fails if a is a pointer and not an array. As 
sizeof(a) then is only the size of the pointer not of the array. 
To make sure to get a compilation error one has to use compiler 
extensions, which gives a non trivial code. Here how to make that 
macro safe in GNU-C

```C
#ifdef __GNUC__
   #define ArrayCount(a) (sizeof(struct {int 
:-!!(__builtin_types_compatible_p(typeof (a), typeof 
(&0[a])));})+sizeof a/sizeof 0[a])
#else
/* A portable variant, but which doesn't check for array or 
pointer. */
   #define ArrayCount(a) (sizeof a/sizeof 0[a])
#endif
```


More information about the Digitalmars-d mailing list