95 points · by mkl95 · 4y ago · 62 comments
I don't have anything better to offer though - C pointers make a whole lot possible in a very terse way.
I'm not sure what to recommend as an optimal learning ISA, though. Ideally something that's mostly RISC, with a small but unified memory model, and no virtual memory, and which has all the math ops that embedded RISC ISAs never bother to implement. (In the end, probably no real architecture ever made that exact set of compromises, and so it'd have to be something made up — some kind of bytecode abstract machine ISA designed specifically to be used in education, an ISA equivalent to languages like Logo or Scratch, or OSes like Minix.)
In practice, I think I would recommend learning assembler by programming for the original Gameboy's LR35902 ISA (which is almost, but not exactly, the Z80/8080 ISA). Not because it's the optimal learning ISA per se, but because it gives you a complete machine including graphical video output, with a compact unified address space (no separate IO-register read/write ops), modern tools that target it, and good emulators that almost always include built-in debuggers and memory viewers — where, as well, the memory is small enough to get it all on-screen and have room left over.
Oh, and unlike other ISAs, where people either never hand-write code for them, or where no hand-written code survives in a readable form, with LR35902 we have several complete projects with hand-written assembly codebases (or, well, reverse-engineered + annotated disassemblies of originally hand-written assembly — just as good!) around to be studied. And, of course, they're just the sorts of things kids interested in computers would be interested in studying the workings of: video games! (https://github.com/pret/pokered is a shining example here.)
Low level languages teach a lot of habits I don't like, and they don't teach as much about working in a modern high level environment on complex software.
Everyone should probably be vaguely competent with C, but I wouldn't call it a top priority.
If you're thinking about the underlying machine stuff when coding in Python, you're kind of just accepting leaky abstractions. If you're in the habit of first principles thinking, leaks seem normal.
C doesn't really seem to layer all that well. Whenever I code in C, I usually have to dig down to the SDK API level, and I wind up reading 10 other files to make a change in 1.
High level languages make it clear when something isn't DRY, or an abstraction leaks, or something isn't usable without modification. It's unusual, you notice right away, and you want to fix it because it obviously doesn't fit.
Low level languages make everything feel totally patched together. Encapsulation just isn't a big thing in most of it. It's almost like looking at an old point to point wired TV set compared to a rack of servers.
You might be able to write some amazing ASM code that feels as modern as some top notch Kotlin... but I'd call that an expert, not just a competent person.
And worst of all, the compiler can't catch many bugs. It's not like Rust. Or even Python. Low level languages don't teach the art of making sure that the computer has your back, the way Rust might. They normalize just entirely relying on your own skill, to the point where some C devs don't even seem to want the compiler to eliminate large classes of bugs for them.
High level languages teach a real appreciation of abstraction and safety, and standardization, that I don't feel like I really learned with C.
Terseness isn't a virtue in and of itself. If terseness helps readability that's great, but unreadable terse code isn't something to aim for.
One of the redeeming aspects of the C pointer declaration syntax is that hairy declarations can be decomposed using typedefs. Improving readability at the cost of reduced density is a good trade.
int i; // variable which is integer
int p@; // pointer that returns integer
int f(); // function returns integer
int f@(); // pointer to function
int f()@; // funtion that returns pointer
int a[10]; // array of ten integers
int a[10]@; // array of ten pointers
int a@[10]; // pointer to and array
int a[10]()@; // array of ten functions that return a pointer
Of course C is stuck with accidents/decisions made 50 years ago. But a language like Go turns all the declaration syntax on its head and still doesn't solve the problem. Rob Pike's blog post says as much (scroll to the bottom section on pointers):https://go.dev/blog/declaration-syntax
He suggests Pascal's caret syntax (^), which wouldn't work if it was also used as the binary xor operator.
The biggest problem with C's pointer syntax is that it's prefix to the value.
int p*
is just as horrible as int *p
because in both cases, it obscures that the type of p is "pointer to integer".C's array and function syntax have exactly the same issue, the entire thing is back-asswards.
Let me demonstrate by converting your examples to a more regular (and logical) language[0]:
let i: i32 // integer
let i: Box<i32> // pointer to integer
let i: fn() -> i32 // function returning an integer
let i: Box<fn() -> i32> // pointer to a function returning an integer
let i: fn() -> Box<i32> // function which returns a pointer to an
let a: [i32;10] // array of 10 integers
let a: [Box<i32>;10] // array of ten pointers
let a: Box<[i32;10]> // pointer to an array
let a: [fn() -> Box<i32>;10] // array of ten functions that return a pointer
Even if you want to shorthand pointers (because you have only one and want it to be built-in), it remains significantly more readable than both C actual and your version.[0] which doesn't mean perfect e.g. one could argue against the special syntax for arrays
Boxes are containers, not pointers or references. Let's look at all of those those using the star syntax and operator inside of an unsafe block? You'll end up with stuff like:
fn main() {
let mut a = [0i32; 10];
let p: *mut [i32] = &mut a;
// Rust did NOT solve this problem
let x: i32 = unsafe { (*p)[1] };
print!("{x}\n");
}
Note the annoying parentheses because they used prefix syntax for pointers, again.There is no actual difference between the two. Pointers and references could have been `Pointer<T>` and `Ref<T>` with the exact same ABI. They're not for UX reasons, one of similarity with C, and one of syntactic overhead.
> // Rust did NOT solve this problem
> let x: i32 = unsafe { (*p)[1] };
That is a debate of precedence, which is a very different concern than what I was replying about, and what TFA is about: the absurd mess that are C type declarations.
However function calls, array subscripts, and field accesses are the same "kind" of operation as dereferencing a pointer. Put the type last if it makes you happy, but you'll have "horrible" syntax if you don't treat pointers the same as the others:
something.bar[10]() // access the field, subscript the array, call the function
something.foo@ // access the field, dereference the pointerNot really? Assuming type and variable names are lexically distinguishable via the lexer hack or, say, capitalization. Here’s an LR(1) grammar (in Grammophone[1] syntax) with postfix types and dereferencing:
stmt -> init ; | expr ; .
init -> decl | decl = expr .
decl -> dtor type .
dtor -> ambi | dfun .
dfun -> ambi ( decl ) | ambi ( darg ) | dfun ^ | dfun ( ) .
darg -> decl , | darg decl , .
expr -> summ | summ = expr .
summ -> prod | summ + prod .
prod -> post | prod * post .
post -> ambi | efun .
efun -> ambi ( expr ) | ambi ( earg ) | efun ^ | efun ( ) .
earg -> expr , | earg expr , .
ambi -> name | ambi ^ | ambi ( ) .
# Stub
type -> int .
name -> x .
It lacks the comma operator or Go-style grouping of multiple variables before a single type, but adding either one is easy and both is possible, though in the latter case the “ambi” hack would need to be extended. I’m willing to believe you could even do this with LL(1) / recursive descent, but the grammar structure would probably end up rather horrible.Whether this is a smart idea as far as ergonomics of syntax errors go, I don’t know.
Don't think I've ever constructed a more complicated type ('directly' so to speak, i.e without typedefs) than an array of function pointers (array of interrupt handlers, taking no arguments, returning void).
99.999(repeating)% of the time I use a typedef for function pointers and nothing looks particular complicated.
And there are a lot of people who want to throw the baby out with the bathwater. Go is the one that really amuses me here: They broke the "declaration follows usage", which I think is a nice idea, and they still have backwards pointer syntax that needs parentheses to get it right.
> Don't think I've ever constructed a more complicated [...]
Heh, I'm not sure this is a great argument. It's kind of like saying you don't care about the complexity/details in floating point because you've never needed more than integers. :-)
There's certainly a tiny trade-off about where to put the core type name. If you have a "let" keyword, your declaration is just a little more verbose:
int foo[10];
let foo: [10] int;
If you don't have type inferencing, you always need to specify the type, and the let keyword and colon are just more noise. I know it's a matter of taste, but I think the first line is cleaner.But my point isn't about where to put the core type (int). It's that pointer dereferencing is the same kind of operation as array subscripting, accessing fields, and calling functions. So unless you put it in order with the rest, you need ugly parens in any general case:
// prefix pointer syntax is convoluted and needs parens:
(*(x.foo.bar))("arguments")[10];
// grab field foo, then field bar, then derefence pointer,
// then call function, then subscript array
x.foo.bar@("arguments")[10]When reading your examples I found myself having to constantly second guess the precedence of arrays and pointers, and I’m not sure how I would declare the type of a function that returns a pointer to an array, or an array of pointers. I’m happy to accept the extra noise of let because it reduces the overall time needed to understand what code means, and we end up reading code so much more than we write it.
[0]: https://nathancraddock.com/blog/consistency-in-zigs-type-sys...
var value: i32 = 0;
This looks like you’re assigning the value 0 to i32, a type. It’s nonsensical. Also what is the purpose of the var keyword? Why not put the type there?The array syntax makes even less sense!
I think what you’re missing in your examples is how the values are used after declaration. C syntax was designed so that declaration resembles use. The reason array subscript brackets come after the variable name is because that’s how you access elements of the array:
int arr[3] = { 12, 76, -42};
arr[1] += 4;
if (arr[2] < 0) { printf(“it’s negative!\n”); } int *foo = &bar;
*foo = 1;
As far as syntax goes, tying the pointer to the identifier doesn't make sense to me, at least. Pointers associated with types makes much more sense: int* foo = &bar;
C++ thinks so too.I would say `v := (p.)` could've been the deref operator, but what do I know.
What fixes this issue is that, like most other languages which are not C, Go understands that "is a pointer" is a property of the type, not the name / value.
So even if it used C-style declaration, Go would say
*int p
or, using a more verbose syntax Pointer[int] p int * a, b; // "Property" of the variable
typedef int * pint;
pint x, y; // Property of the type
This has created so much bad legacy code where pointer typedefs are created for no good reason. template<typename T>
using ptr = T*;
ptr<const char> str:
const ptr<char> pchar;
ptr<void(ptr<const char>)> fun_ptr;
Basically this simple trick removes most of the confusion, and you can read the types left to right. using func_ptr = float(int);
// Given
float some_func(int);
// Then
func_ptr* a = &some_func;
// Also
func_ptr* b = [] (int x) { return 0.f; };Also for what it's worth, this isn't 'human readable' either, or is it?:
"declare foo as pointer to function (pointer to const void) returning pointer to array 3 of int"
apt install cdecl
And then do it on the command line. But hey, let's turn everything into a web service, with monitoring as a bonus feature.(Repost of https://news.ycombinator.com/item?id=11164685)
See https://news.ycombinator.com/item?id=5080081 and https://web.archive.org/web/20190714064656/http://cseweb.ucs...
Maybe "declare bar as volatile pointer to array of 64 const int" will sound more smooth? :)
0 - https://mobile.twitter.com/derwlang/status/15057099820246712...
for(int i = 0; i < x; i++)
into "declare 'i' as int and assign '0' to it; while 'i' is smaller than 'x' do ... and increment 'i'."
2) It is not necessary.
C's terse syntax is not hard to understand for anyone who actually uses the language. Most of the comments here are from people who do not.
declare xyzzyx as pointer to pointer to array 153 of const double int foo, *bar, baz(), (*zyzzy())();
i do not understand why blowhard rob pike types dislike it. its exactly the kind of elegant you would think they would like