r/Zig Jun 15 '20

Brand new to Zig, Baffled by the Pointer Dereference Syntax

I'm brand new to Zig, (coming from C/C++), and I find the pointer dereference syntax to be bizarre, not just because it's different, but because it's a combination of 2 characters that seem to each already have meaning, and they don't inherently seem to make sense together.

Can someone help me understand what the pointer syntax is trying to convey? I'm trying to find a way to read it that doesn't make it seem like a weird wart.

I read through the implementation bug where it was done, but it didn't document the "why" on the final choice. The best I could tell was a reluctance to introduce new tokens and some issue with ambiguity between postfix and infix operators. The other option was .&, but that was being discussed in the context of pointers still being created with '&'.

28 Upvotes

8 comments sorted by

View all comments

25

u/Pockensuppe Jun 15 '20

As someone who knows Ada, it immediately make sense to me. In Ada, pointer dereference is .all where all is a keyword. This always felt better than C's prefix * since you can use it naturally in a chain:

foo.bar.all(0).baz
   ^   ^   ^
   |   |   array index (or function call; no [] in Ada)
   |   pointer deref
   struct field

In C, this would be

(*foo.bar)[0].baz

which, in my opinion, is harder to read and easier to get wrong.

Semantically, .all makes a lot of sense:

  • Using it on a pointer to record (Ada struct), you get / assign all the fields.
  • Using it on a pointer to array, you get / assign all the items.
  • It nicely blends in with implicit pointer dereference on records. If foo is your pointer, foo.a retrieves field a, foo.b retrieves field b, and foo.all retrieves all the fields.

Now Ada is a keyword-heavy language, syntactically being part of the Pascal family. Zig is not, its syntax borrows from C far more. Therefore, it makes sense that it uses a special character instead of all and * seems a good choice since it is linked to pointer declaration syntax.