https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108483
Bug ID: 108483
Summary: gcc warns about suspicious constructs for unevaluted
?: operand
Product: gcc
Version: 10.2.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: gcc-bugzilla at mkarcher dot dialup.fu-berlin.de
Target Milestone: ---
Created attachment 54318
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=54318&action=edit
minimal example
A well-known construct to determine array sizes at compile time is
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(*(x)))
gcc helpfully warns for dangerous mis-use of this macro, as it only works with
real arrays, not with pointer, for example. Assuming NULL is defined as
((void*)0), ARRAY_SIZE(NULL) yields a valid C expression, as long as we use the
gcc extension that sizeof(void) equals one:
ARRAY_SIZE(NULL) is expanded to essentially sizeof(void*)/sizeof(void)
which yields 8 on usual 64-bit systems and 4 on usual 32-bit system. While this
expression is valid, the result of this expression is likely not what the
programmer intended, so the gcc warning "division ‘sizeof (void *) / sizeof
(void)’ does not compute the number of array elements" is warranted.
The Linux kernel contains a macro essentially being
#define ARRAY_SIZE_MAYBENULL(x) ( __builtin_types_compatible_p(typeof(x),
void*) ? 0 : (sizeof(x)/sizeof(*x)) )
which is intended to be invocable using actual array operands (returning the
array size) or the compile-time constant NULL (returning zero).
gcc correctly evaluates ARRAY_SIZE_MAYBENULL(NULL) to zero, but emits about the
suspicious pattern in the third operand of the ternary operator. This is not
helpful for the programmer, and breaks builds using -Wall -Werror.
This is a feature request to omit warnings about dubious constructs like this
if it can be statically determined that they are not evaluated.
The example in the attachment compiles correctly and initializes x to 1, but
emits the spurious warning about the unevaluated sizeof pattern.