<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/102836>102836</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
C: Add __lengthof__ operator
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
alejandro-colomar
</td>
</tr>
</table>
<pre>
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).
The specifications of the operator are:
```
The keyword __lengthof__ determined 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.
Also, are you interested in this feature?
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVl2P4joS_TXmpQQKDjTwwEPDLLstrbQr3dF9bVXsCrjHsSPbgeb--qtywufM9MOVEKA4dVxV59SxMUazd0RrMd-I-bcRdungwxotfaDTwY-Vt77BMKq8Pq__Y4SciuKbK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