On 28/05/2020 23:01, Xavier Del Campo Romero via Gcc wrote:
Hello gcc team,

I have sent the following proposals to the committee, but they require them to 
be implemented at least into two major compilers, so I am proposing them to be 
implemented into gcc. This is going to be a rather lengthy e-mail, so TL;DR:

Proposal 1: New pointer-proof keyword _Lengthof to determine array length
Motivation: solve silent bugs when a pointer is accidentally used instead of an 
array

In gcc, the simple "#define ARRAY_SIZE(a) sizeof (a) / sizeof *(a)" gives a compile-time warning if passed a pointer, since the introduction of "-Wsizeof-pointer-div" in -Wall in gcc 8.

I am not convinced that anyone who would be careful enough in their coding to use such a new "_Lengthof" feature would not already be using "-Wall" at least. So for gcc, the new keyword would, I think, be useless. And for any compiler without an equivalent warning (clang has it from version 7), it would likely to be easier to add the warning rather than the keyword.

Many people have figured out alternative "ARRAY_SIZE" macros that work with existing compilers and give compile-time warnings on naked pointers. But like your suggestion below, they rely on compiler extensions such as gcc's "typeof".


So my counter-proposal for you would be to recommend gcc's "typeof" as a new keyword (spelt "_Typeof", with "typeof" as a macro in <stdtypeof.h>, in solid C tradition).

Then you have a feature that has a long-established history in two major compilers (gcc and clang, at least), has been massively used in real-world code for decades, and has a huge range of useful use-cases. Get "typeof" into the C standards and many people will thank you! And then your _Lengthof becomes a simple macro that can be put in a standard header file, and needs no established implementation to be acceptable. (And you don't need any help from gcc or clang, except perhaps for describing the details of the semantics of "typeof".)

Reply via email to