C++ Logo


Advanced search

Re: [std-proposals] Small C compatibility extensions for array

From: Alejandro Colomar (man-pages) <"Alejandro>
Date: Wed, 26 Oct 2022 10:41:18 +0200
Hi Thiago,

On Tue, Oct 25, 2022, 21:57 Thiago Macieira via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Sunday, 23 October 2022 12:28:41 PDT Bo Persson via Std-Proposals wrote:
> > So instead of f(int [static 42]) you could use f(std::array<int, 42>&).
> >
> > Being C compatible is a very minor convenience here.
> Strictly speaking, that's not the same thing. The "static 42' means "at
> least
> 42", not "exactly 42". See https://cigix.me/c17#
> To declare "exactly 42", the C standard decided to overload yet another
> keyword: restrict. You write:
> f(int [static restrict 42]);
> C++ does not want this.

This is incorrect. 'restrict' is not overloaded in C, AFAIK. The
declaration above means (ignoring the fact that implicit int is not valid
anymore) "function f accepting a single parameter, which points to a
storage of at least 42 int, and is not aliased by any other pointers
(though this is redundant by the fact that it's the only parameter).

There's simply no way to specify an exact size to a (false) array parameter
(and it usually is unnecessary; so much that the thing I'll show below is
seldom used or even known)

The only way you can specify a fixed-width array parameter in C is through
a pointer to an array:

void g(int (*a)[123]);

This will guarantee at compile time that any array being passed is exactly
of size 123, or compilation will fail because of type mismatch.

However, it complicates the syntax a little bit, since you now need to add
a level of indirection in the code.

As a curiosity, I guess this is how the origins of C++ arrays were
implemented (but that's just my guess).


> --
> Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
> Software Architect - Intel DCAI Cloud Engineering
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2022-10-26 08:41:32