152 points · by aragonite · 2y ago · 131 comments
In B the only type is the machine word, which can perform arithmetic and be dereferenced. Arrays the only special kind of declaration and are declared like
auto foo[10]
Where auto is a storage class specifier like extern or static.In that world, having declaration follow usage makes perfect sense. There's no "other" kinds of data to worry about, the operators you can apply to an expression describes its type exactly.
The "fix" would be to not have arrays decay. I believe C++ could probably get there if it had taken Epochs, I further believe taking Epochs (P1881) when it was proposed would have been extremely disruptive but perhaps possible and worth attempting. I do not believe it's still possible, the moment passed and with it, in my view, any hope of salvaging C++.
Without Epochs, any and every such change to C++ is similarly disruptive and that's too expensive so more or less nothing gets fixed, instead layers of kludges must be added. That's how Foonathan ends up with: class foo final trivially_relocatable namespace() { … };
As for the billion dollar mistake, a null pointer reference results in a seg fault. But the array decay results in buffer overflows, the #1 problem in shipped C code, and the buffer overflows result in memory corruption. Memory corruption is much, much, much worse than a seg fault. For example, buffer overflows are exploitable by malware. Seg faults are not.
Hence, the array decay is the worst mistake.
We invent new languages almost daily and none of them have ever resolved the problem. I mean, when you start with a pointer, it's uninitialized. Setting it to null is much better than having it point somewhere, where there might be incorrectly interpreted data.
So, null. We have Java, suffering the same problem, Golang suffering the same problem and Rust, where you have the same problem if you call unwrap, without checking that all code paths ensure you have the value populated.
Seems to me this is an inherent problem of using an uninitialized value... so, what is the mistake?
Those operators are the same ones you would use in an expression to use your declared object. They are the unary dereferencing operator, the array subscription operator, the function call operator and the parentheses for overcoming default precedence.
This was the biggest mistake IMO. Go’s declaration syntax needs colons, it would have been 100x more readable.
Compare:
func foo(x int, y int) int {
var sum int = x + y
return sum
}
To: func foo(x: int, y: int): int {
var sum: int = x + y
return sum
}
The colons would have made it so much more clear to read for me. func foo(x: int, y: int): int {
sum : int = x + y
return x + y
}
With type inference the type declaration just collapses out to what you have now. func foo(x: int, y: int): int {
sum := x + y
return x + y
}
I've seen it in a few languages and it has seemed quite nice in use and appearance to me. return sumI can only assume he removed them, not for brevity, but as a compromise for the sake of C programmers to only ask them to learn one new thing rather than two.
int func foo(int x, int y) {
var sum = x + y
return sum
} foo :: proc(x : int, y : int) -> int {
sum : int = x + y
return sum
}
or foo :: proc(x : int, y : int) -> int {
sum := x + y //
return sum
}So instead of this:
func foo(x: int, y: int): int {
var sum: int = x + y
return sum
}
You’d have this instead: func foo(x :int, y :int) :int {
var sum :int = x + y
return sum
}That makes as much sense as `int *i`, when `int* i` is obviously the correct (though heterodox) way.
Although if I was writing this myself, I would split it up like so:
typedef char *StringArray[];
typedef StringArray *Func();
Func **foo[][8];
Which is equivalent and much easier to read. (Although still not trivial. I have no idea what purpose this type really serves. The type names are placeholders as a result.)C type declarations become particularly tricky specifically when people try to directly declare (or typedef) pointers to functions/arrays without an intermediate typedef for the function/array type.
So if you make it a rule to typedef array types before creating pointers to them (although this usually makes for some rather unreadable code so maybe try avoiding it in general) and to typedef function types before creating pointers to them, you will usually have much more readable code.
As a bonus, you can then use the function typedef to provide an early type-check for a callback function (even if it's a callback your code doesn't directly use). E.g.:
typedef int Func(int a);
Func foo;
int foo(int a)
{
return a * 2;
}
Or, you know, switch to a higher level language. if ((Lflag ? chown : lchown)(p->fts_accpath, s->st_uid, -1))
(void)printf(" not modified: %s\n",
strerror(errno));
which relies on the function prototypes of the chown(2) and lchown(2) syscalls being otherwise identical.cdecl> declare bar as const pointer to array 5 of pointer to function (int) returning const pointer to char
char * const (( const bar)[5])(int )
Also online at https://cdecl.org/
But maybe also because I changed up my general programming approach a bit and try to think a bit longer before hitting up a search engine. Also forced myself to read more reference sheets than stackoverflow or chatgpt. And I must say, this made me a lot more comfortable, because I understand more. Can recommend to go through the struggle/10
The same trick works for anything you want to typedef!
Consider this type declaration in Go:
func(string) []func(int)[]*float64
This took me 5 seconds to write. The C/C++ counterpart would probably take an hour to get right :(What a pointer to function (int) returning int?
The difficult way:
int (*p)(int);
The easy way: typedef int Func(int);
Func *p;
The typedef reads just like a normal function declaration except for the name is the type name rather than the function symbol name. Just like a function declaration, you can add more documentation by giving the parameters names. e.g.: // used for some hypothetical allocator API
typedef void *Alloc(size_t size);
Similar trick can be used for pointers to arrays (just typedef the array type). Although in practice pointers to arrays just make for awful code.Oh, functions can't return arrays in C. That would be a pointer. Well, that makes it easier.
double **(**(*)(char *))(int)
It did take a couple minutes, but I just woke up. Also, idiomatically there would be a typedef: typedef double **A(int);
typedef A **B(char *);
B *
That took a few seconds to write. char *(*(**foo [][8])())[]
then reads ascharへのポインタの配列へのポインタを返す関数へのポインタへのポインタの8要素からなる配列の未定サイズの配列
which uses the reverse of English possessive, and object verb order.
Imagine how much easier that last example would be with a trailing return type, Ptr<> and Array<> parametrised types, and lambda-esque function objects instead of function pointers:
char * (*(**foo[][8])())[]
versus let foo: Array<Array<Ptr<() -> Ptr<Arr<Ptr<Char>>>>, 8>> = ...
It's immediately clear what the top-level type of `foo` is: some parametrised `Array`. We can do better, though.In this hypothetical language, one would probably dispense with 'pointer to char' and 'pointer to array' and replace them with view/range/span types, eliminating a layer of type parametrisation and many classes of bugs:
let foo: Span<Array<Ptr<() -> Ptr<Arr<StringView>>>, 8>> = ...
Though I am dumbfounded by why there needs to be a 'pointer to array' in the function return type, and a 'pointer to function pointer'. I assume these are unknown arrays themselves, which means... let foo: Span<Array<Span<() -> Span<Arr<StringView>>>, 8>> = ...
A perfect language would probably have multi-dimensional spans, which would eliminate the two `Span<Array<>>` and replace with some `MultiSpan<>`.Addendum: https://cdecl.org/ is a very useful and very self-aware resource: 'C gibberish ↔ English'.
Rule #1 of programming is to make code easy to understand and self-documenting. This should be a sequence of typedefs with self-explanatory names followed by a function call taking one pointer or type and returning another.
Array<Ptr<(Int, String) -> Bool>>
Should be:
Array<OnClickCallback>
Applying that to C code keeps the insane decls in check, especially when using function pointer types
#define _Ptr(T) typeof(T\*)
#define _Array(T,N) typeof(T[N])
_Ptr(_Array(int, 8)) x = ...
and one can also define view and span types in C. No hypothetical language needed. But I do not think this is an improvement.(Also funny, multi-dimensional spans are coming in the form of TensorSpan<T>)
Could we have done without pointer arithmetic? Could we have hidden the pointer part of function pointers and made them syntactically just like Python or JS functions?
Did arrays as raw blocks of memory ever need to exist?
I remember when I first learned C, I didn't really see the problem, I thought it was a perfectly fine language, until I learned Python/JS/C++/Dart and saw how nice high level features and package management is.
But now I wonder how I ever used it at all without complaining!
char * foo[10][5];
The OP article shows you how to actually read the declarations, not a fake trick that will lead you astray. $ sudo apt install cdecl
[…]
$ cdecl
Type `help' or `?' for help
cdecl> explain char *(*(**foo[][8])())[];
declare foo as array of array 8 of pointer to pointer to function returning pointer to array of pointer to char
cdecl> const foo: [_][8]**fn () [*][*:0]const u8;
This is an array of result-defined size, of arrays of eight pointers to fn pointers, which returns a many-item pointer to null-terminated arrays of u8. Null terminated because we're going to assume that the C data structure is properly null-terminated...Still an insane data structure, and I'm still learning Zig, so I can't promise this is precisely equivalent to the C, I got as close as I could and am unwilling to try and compile, let alone build, such a type.
No one would actually do this unless they needed `extern` compatibility. Ignoring the fact (pointed out in the Fine Article) that no one would use anything vaguely like this, a more Zig native version might be
const foo: [_][8]**fn() [][]const u8
Which returns a slice of slices of immutable u8s, these being fat pointers which include their length. seq[array[8, ptr ptr proc(): ptr seq[ptr char]]]]
I love having actual words instead of random punctuation soup.I believe dcl mimics the cdecl program.
char*[]*function()[8][] foo;Plus the fact that arrays in type names sometimes act as pointers and sometimes not.
The best shot is to name intermediate types, since they aren’t really intermediate most of the times. Properly structured programs tend to disassemble complex structures to work on them, so you need these names anyway.
That said, C compilers definitely lack -Wunreadable-types flag which must be default.
It is a widely accepted practice to typedef pointers to functions.
With pointers, more than 2 levels of indirection is an indication of a badly written program.
In practice, the most complex declarations you should write are "pointer to pointer to x", "array of pointers to x", "array of function pointers returning x". Stuff like "pointer to function returning pointer to pointer to array" is nonsensical most of the time.
Foo : array (Positive range 1 .. 100) of access function return access Integer; uggclang: error in integer literal, did you mean "ONE HUNDRED"? at line oneAll syntax is horrible. Rust is the en vogue tool of the moment and it's objectively harder to read than C. Python used to be clean and now it's sort of a mess. C++, well...
Some languages try to get away with having simple syntax though. Javascript is in this camp, as of course are all the Lisps. And the result is that you end up drowning in a sea of complicated semantics instead, c.f. the famous "wat" video or the fact that every sexpr macro-ized DSL works like its own little butterfly.
You can't win. C is fine. Could you do better if you started from scratch? Sure. Would it last? No.
I think you're just used to C syntax. I find Rust syntax much easier to read than C syntax (and that was already true when I didn't know either language well).
If this is "objectively" true please link the study which was able to somehow measure that.
That said, C's syntactic missteps appear to be accidents, while Rust delights itself in being ugly.
Rust has an innovative, but highly opinionated, memory model: the premise is writing high performance memory safe programs, with 'zero cost' abstractions and so on. You might write a program in Rust rather than C in the way you might write a program in Go rather than C: because the application is better modeled in a language which isn't C. For programs which pertain to the domain where C should be considered on its merits, if you try to write them in Rust, you may as well start each module with an unsafe block.
But no, C is not fine. It has a stunning amount of own-goals making it pointlessly difficult to write a program with a fine-grained memory policy that is correct. C also doesn't have a syntax at all until you've run CPP, and then you have a context-sensitive parse. Neither of these are mere technical formalities, they actively inhibit understanding a C program.
This is often said, but does not reflect reality. At this point, we have tons of bare-metal and OS-level Rust code existing in the world, and it still has very little unsafe overall.