Comment

Comment by WalterBright

> int flex[] __attribute__((__element_count__(items)));

While what the article describes is clever, it is needlessly complex, and filled with various compiler switches and extensions.

In contrast, here's a stupid simple approach:

https://www.digitalmars.com/articles/C-biggest-mistake.html

where bounds-checkable arrays are declared as:

    int a[..];
`a` consists of two fields, a `length` and a `pointer`. Indexing it means the compiler can (optionally) insert a bounds check it.

    int s[..] = "string";
    s[10] = 'x'; // fatal runtime error
We can turn a pointer into a bounds checked array by "slicing" it:

    int *p = (int*) malloc(10);
    int a[..] = p[0 .. 10];
A bounds checked array can be turned into a pointer:

    int *p = &a[3];  // point to 3rd element of a[..]
That's all there is to it. No pages and pages of compiler switches and extensions.

Does it work? We've been doing that with D for over 20 years. Hell yeah, it works. It works fantastically well. It does not disturb any existing C code.

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton