4 ms·
In C a pointer can point to any arbitrary offset within an object or array, to a local variable somewhere on the stack, to a static variable, to read-only memor
by mannschott 2mo ago
In C a pointer can point to any arbitrary offset within an object or array, to a local variable somewhere on the stack, to a static variable, to read-only memory, to the first(?) of an indeterminate number of characters (hopefully) terminated by ((char)0). To the first of a statically unknown number of variables located somewhere in memory, to a variable of indeterminate type (thanks to union), to I/O devices, and also to unallocated memory since there's no bounds checking.
A reference can only point to an object or an array on the heap. Array indexing is bounds-checked.
It seems obvious to me that these restrictions make references easier to reason about than C-style pointers, and therefore easier to learn.
- IsTom 2mo agoI imagine most of these examples (besides strings) isn't something you learn in the beginning and when e.g. doing operations on linked lists you're pointing to either allocated structs or null.
- jjav 2mo agoYou tend to learn it early not by choice, but because the student makes some operation on the pointer and suddenly all they get are core dumps or (seemingly) bizarrely corrupted data and they have to confront what's going on early in the learning process.
- kbelder 2mo ago>It seems obvious to me that these restrictions make references easier to reason about than C-style pointers, and therefore easier to learn. I came to C from Assembly, so maybe I'm in a different camp, but references seem to me to be more difficult to reason about than pointers. Pointers just are, like math; references seem like a bunch of semi-arbitrary conventions. Like the difference between writing SQL and using an ORM, which is supposed to be simpler but ends up being messier.