Closed
Description
Hi!
I've sent a patch set to GCC for adding a __lengthof__
operator:
https://inbox.sourceware.org/gcc-patches/20240728141547.302478-1-alx@kernel.org/T/#t
There's a related proposal for ISO C (wg14):
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2529.pdf
(although the proposal is old (not authored by me), and isn't as curated as the GCC patches). I have the intention of refining that proposal and sending a new one.
The specifications of the operator are:
The keyword __lengthof__ determines the length of an array operand,
that is, the number of elements in the array.
Its syntax is similar to sizeof.
The operand must be a complete array type or an expression of that type.
For example:
int a[n];
__lengthof__(a); // returns n
__lengthof__(int [7][3]); // returns 7
The result of this operator is an integer constant expression,
unless the top-level array is a variable-length array.
The operand is only evaluated if the top-level array is a variable-length array.
For example:
__lengthof__(int [7][n++]); // integer constant expression
__lengthof__(int [n++][7]); // run-time value; n++ is evaluated
There are a few interesting reasons why this feature is better than just a macro around the usual sizeof division:
- This keyword could be extended in the future to also give the length of a function parameter declared with array notation and a specified length.
- This macro causes a compiler error if the argument is not an array (it's a constraint violation).
- It results in a constant expression in some cases where sizeof would evaluate the operand. For example:
__lengthof__(int [7][n++])
. - It only evaluates the operand once for VLAs, where the sizeof division would evaluate twice (one per sizeof call).
Please feel free to give any feedback for the feature in the GCC thread.
Are you interested in this feature?