https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121270
Bug ID: 121270 Summary: New diagnostic: -Wsizeof-array Product: gcc Version: 16.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: foss+...@alejandro-colomar.es Target Milestone: --- Now that we have _Countof(), I'd like a diagnostic that completely prohibits sizeof(array). Once can get the number of elements with _Countof(array), and the size in bytes with _Countof(array) * sizeof(array[0]). The benefits of avoiding all uses of sizeof(array) are: - Code can't accidentally be passed an array parameter where an array is expected. There's already -Wsizeof-array-argument, and it's enabled by default, but it might still confuse some programmers. If we get rid of sizeof(array) everywhere (or in as many places as possible), and tell programmers to derive it from _Countof(), programmers will be more educated about this. - The idiom will work with array parameters out of the box, once (if) we enhance _Countof() to work with array parameters. This would encourage programs to wrap APIs in macros such as #define STPRINTF(s, ...) (snprintf(s, _Countof(s), __VA_ARGS__) >= _Countof(s) ? -1 : 0) which would prevent many bugs by not having chances of accidentally specifying a bogus size argument. This diagnostic, of course, should not be part of -Wall, as it would trigger on working code, but it could be part of -Wextra if we want to promote using _Countof(array) from now on. Programs could define #ifndef countof #define countof(a) (sizeof(a) / sizeof((a)[0])) #endif As compilers that are old and don't have countof will not have this diagnostic either, and so using sizeof(array) there would be fine.