[Bug c/108483] gcc warns about suspicious constructs for unevaluted ?: operand

jakub at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Fri Jan 20 21:59:58 GMT 2023


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108483

Jakub Jelinek <jakub at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |jakub at gcc dot gnu.org

--- Comment #5 from Jakub Jelinek <jakub at gcc dot gnu.org> ---
If you don't want to see the warning at all when using the macro, workaround is
easy, just use (0+sizeof(x)/sizeof(*(x)) and be done with it.
If you want a warning if you use it say on int * type and no warning but 0
result if you use it on cv void * (note, the original
one only works with void * and not with const void * etc.), you could use e.g.
following (verified both with gcc and clang),
of course if you don't care about const void * etc., you can simplify it a
little bit.

//#define ARRAY_SIZE_MAYBENULL(x)  ( __builtin_types_compatible_p(typeof(x),
void*) ? 0 : (sizeof(x)/sizeof(*(x))) )
//#define ARRAY_SIZE_MAYBENULL(x) _Generic((x), void*: 0, const void*: 0,
volatile void*: 0, const volatile void*: 0, default:
(0+sizeof(x))/sizeof(*(x)))
//#define ARRAY_SIZE_MAYBENULL(x) _Generic((x), void*: 0, const void*: 0,
volatile void*: 0, const volatile void*: 0, default: sizeof(x)/sizeof(*(x)))
#define ARRAY_SIZE_MAYBENULL(x) _Generic((x), void*: 0, const void*: 0,
volatile void*: 0, const volatile void*: 0, default: \
  sizeof(x)/sizeof(_Generic((x), void*: (x), const void*: (x), volatile void*:
(x), const volatile void*: (x), default:*(x))))

void
foo (int *p)
{
  int a[10];
  p[0] = ARRAY_SIZE_MAYBENULL (a);
  p[1] = ARRAY_SIZE_MAYBENULL ((void *) 0);
  p[2] = ARRAY_SIZE_MAYBENULL ((const void *) 0);
  p[3] = ARRAY_SIZE_MAYBENULL ((volatile void *) 0);
  p[4] = ARRAY_SIZE_MAYBENULL ((void *restrict) 0);
  p[5] = ARRAY_SIZE_MAYBENULL ((const volatile void *) 0);
  p[6] = ARRAY_SIZE_MAYBENULL (p);
}


More information about the Gcc-bugs mailing list