12 ms·
Tl;dr: It is just pointer dereferencing. I.e. C's *ptr is ptr.* in Zig.
by copx 2y ago
Tl;dr: It is just pointer dereferencing.
I.e. C's
*ptr
is
ptr.*
in Zig.
- cardanome 2y agoYeah, I kept on reading to find out if there is some Zig-specific twist but it is literally just that. Are there really that many Zig programmers that have never seen C or know what pointers are?
- spacedcowboy 2y agoAnd why change something like that? The world would be a better place, IMHO, if there were less different ways to write something from language to language. Sometimes it seems like the change is just to make it different, not better.
- IshKebab 2y agoSame reason Rust uses foo.await instead of await foo. It's clearly superior syntax. The whole point of Zig is to fix C's mistakes. I don't know why they'd repeat this one.
- moomin 2y agoI’ve gotta say, when I first learned Rust had gone its own way on await, I was heavily sceptical. But seeing the actual examples was pretty compelling.
- IshKebab 2y agoYeah I was skeptical too but it makes so much more sense. Now I'm constantly thinking "this is dumb" when using other languages with the "normal" syntax. I wish they'd got it right for (de)referencing too though.
- dcsommer 2y agoI think Rust could use some syntax improvements for pointer manipulation. It has suffix .await, so maybe the community is ready for suffix .* for dereference now too. Visually scanning left and right, along with the extra parentheses, makes pointer-based code in Rust worse than C++ almost. A fully left-to-right syntax would be amazing. EDIT: found https://github.com/rust-lang/rust/issues/10011 https://github.com/rust-lang/rust/issues/10011 and https://github.com/rust-lang/rfcs/pull/3577 https://github.com/rust-lang/rfcs/pull/3577
- throwawaymaths 2y agowhy is foo.await better? is it a method call? is it a property/field value? how am i to be indicated that there is an implicit suspend point when you .await?
- dcsommer 2y agoIt preserves a left to right reading of the code. You don't have to jump visually elsewhere.
- vvillena 2y agoYou will know because any text editor or IDE worth the name will light up that ".await" in such a way you will immediately know it's not a method call or a struct field. The entire construct, including the dot, is a postfix keyword.
- rezonant 2y agoIt's the difference between (await (await foo).bar).baz and foo.await.bar.await.baz -- which do you want to write?
- int_19h 2y agoIn general, the rule of thumb is that prefix and postfix operators don't mix well in a single expression - order of operations is confusing, and reading the code requires going back and forth to follow it. In the ideal world, we wouldn't have unary prefix operators at all, but unfortunately unary +, -, and NOT are prefix mostly because they were that in math notation and got grandfathered in (bonus points to Smalltalk here for going with consistency here - "not" and "negated" are regular nullary methods there so it's postfix throughout!). However, these are rarely themselves an operand of another unary operator, so you can mostly deal with this by giving postfix higher precedence than prefix in all cases, so at least it's a simple rule. But then for pointer dereference, it is in fact common to have the result of a dereference itself be an operand in the middle of another expression. So now you have some choices to make. If you make the pointer dereference prefix, then you don't need extra parentheses when applying other prefix operators to it, e.g. -*p or !*p. If you make it postfix, then you don't need extra parentheses when applying other postfix operators to it, e.g. (using Pascal-style ^ for dereferencing) p^[0] or p^.x. Alternatively, you could add special postfix operators that desugar into the combination but avoid those extra parens, which is what C did with -> for field access. (Technically, you could also make everything prefix instead, e.g. field access ALGOL 68 style: `month OF birthDate OF person`. But this is very counter-intuitive with indexing, and also makes code completion unusable, so it's not a serious option.)
- FlyingSnake 2y agoAt this point &var and *var are pretty much an established way across languages, like if-else. I don’t see any benefit of reinventing this paradigm.
- epolanski 2y agoThe fact that the author of Zig who's extremely well versed in C and C++ went this way should make you at least try to think why he went that way before dismissing it.
- FlyingSnake 2y agoSounds like Appeal to Authority fallacy.
- xigoi 2y ago> Copying bad design is not good design. —Andreas Rumpf
- nineteen96 2y agoAgreed. And p.* is remarkably unintuitive and nonsensical compared to *p.
- int_19h 2y agoIt's remarkably intuitive and sensible if you remember that . in Zig auto-dereferences for field access and then treat `*` in this construct as field name denoting the entire object. Ada does the same exact thing, except there you write `p.all` instead. In any case, while the exact syntax may not be ideal, using a postfix operator for dereferencing is vastly better than prefix in practice due to typical patterns of use. There's a reason why you end up writing () a lot in C code with heavy pointer operations - the things they end up mixed with most often turn out to have the wrong kind of priority and/or precedence more often than not. Things are much simpler when everything is postfix and code reads naturally left-to-right.
- IshKebab 2y ago
- 3836293648 2y agoPostfix is only superior when you have lots of things to chain. C doesn't have any chaining at all. f(g(x)) is just as good as f(g(x))
- card_zero 2y agoGotta escape those asterisks so you don't output italics. f(*g(*x)) is just as good as f(g(x*)*) Hmm, function names go before parentheses, that looks like a good reason for dereferencing to be prefix too, otherwise they end up a long way apart. But in the back of mind I'm thinking "semantics cause pointless fussy arguments, all code is ugly, let's stop programming in text somehow".
- 3836293648 2y agoOh yeah, forgot HN supported some markdown. But this is literally not semantics. Semantics is everything of value, this is just syntax.
- card_zero 2y agoSorry, yes, syntax. I was equating it to "purely semantic argument", arguing about the meaning of words. Here about it's where to put symbols.
- dfawcus 2y agoOne is able to chain calls in C via: x()->g()->f(); At least one person at Bell Labs historically used that scheme for some graphics program. All it requires is that the function returns a pointer to a struct which itself contains function pointers. C also allows the dot form if you really want it: x().g().f() Simply by returning structs, and for all compilers that I know if, such end up using a hidden pointers to structs. Now to make it a bit more usable, one needs a bit of planning so that either of these can be done: x(&x_out).g(&g_out, x_out).f(&f_out, g_out); x(&x_out)->g(&g_out, x_out)->f(&f_out, g_out); (I'd suggest the latter is now the more readable of the two). Where there is a VFT in each of the xxx_out structures, and the calls simply returns the VFT, while the whole abstraction is stored/returned via the out arguments.
- throwawaymaths 2y agooh no. this is DEFINITELY a place where zig made a GOOD change away from c. when a value is dereferenced, having a consistent left to right dereferencing makes sense. for example, in c, without looking up the order of operations how confident are you that you know what is going on in the following: foo = **bar[10]
- wat10000 2y agoIf prefix * bugs you, C has a suffix deference operator as well, `[0]`. (Yes, C programmers will probably hunt you down if you do this, but it does work.)
- throwawaymaths 2y agothis is not just a preference but a practical matter, esp. for reading nd checking other People's code. did you solve the puzzle at the end with high confidence?
- wat10000 2y agoYou mean `foo = *bar[10]`? That’s equivalent to `bar[10][0][0]`, i.e. the array element access is done first, then the retrieved element is dereferenced twice. I’m quite confident in this, but I’m a systems programmer working in C++, so that’s my bread and butter.
- deleted 2y ago[deleted]
- throwawaymaths 2y agoit's hard to disambiguate from bar[0][0][10]...
- wat10000 2y agoSure, I see your point and suffix does seem like the better option. But for people who do a lot of C, it’s not an issue.
- sudahtigabulan 2y agoIt's not just different. This syntax is less arbitrary than C's. It draws a syntactic parallel between accessing a single member and accessing "all members". (by using pattern-matching-like syntax) It makes the language more consistent and one's mental model of it smaller. (Even though I doubt that patterns other than the Kleene star would work) A parallel with files: cp dir/a dir/b dir/c /other/dir In Zig you can cp dir/* /other/dir In C: cp *dir /other/dir
- spacedcowboy 2y agoI don't actually agree that it makes the mental model smaller. I see something that is just different from what I expect, is cognitively jarring, interrupts the flow of what I'm doing, and forces me to focus on something I shouldn't need to. But it seems like I'm in the minority, so maybe it's just "old man shouts at clouds", I'll just ignore the language and move on :)
- latch 2y agoAuthor here. I agree this is a less-than captivating piece. I write a lot about Zig and wanted something I could reference from other pieces. But, to answer your question directly: absolutely. In addition to writing a lot about it, I maintain some popular libraries and lurk in various communities. Let me assure you, beginner memory-related questions come up _all the time_. I'd break them down into three groups: 1 - Young developers who might have a bit of experience in JavaScript or python. Not sure how they're finding their way to Zig. Maybe from HN, maybe to do game development. I think some come to Zig specifically to learn this kind of stuff (I've always believed most programmers should know C. Learning Zig gets you the same fundamentals, and has a lot of QoL stuff). 2 - Hobbyist. Often python developers, often doing embedded stuff. Might be looking to write extensions in Zig (versus having to do it in C). 3 - Old programmers who have been using higher level languages for _decades_ and need a refresher. Hey, that's me!
- sundarurfriend 2y agoHey, that's me too! Also, from learning human languages, it's a well-known lesson that phrasebook-type "this means this" translations (like some here are asking, from Zig to C/Rust) are useful for quick and dirty learning good enough for one trip, but long term learning needs this kind of a direct explanation. 1. It avoids the word (or syntax in this case) getting stuck in a double-indirection state, needing you to mentally translate it from Zig to C to what it actually means every time. 2. It avoids the learner attaching the wrong nuances to the word or syntax feature, based on the translation they're given, when the language they're learning has different nuances. In other words, it helps the learner see it as its own thing, and not be unduly colored by what they already know and find easy to grasp on to (even when it's subtly wrong).
- Measter 2y ago> Also, from learning human languages, it's a well-known lesson that phrasebook-type "this means this" translations (like some here are asking, from Zig to C/Rust) are useful for quick and dirty learning good enough for one trip, but long term learning needs this kind of a direct explanation. This is also good when the user already knows the concept. Like, I'm a reasonably competent Rust user, and when I started playing around with Zig I already understood the majority of concepts at play and just needed to know how Zig spelled them. But I still needed that more in-depth explanation for concepts I was less familiar with (comptime being the main one).
- epolanski 2y agoI know some C but I haven't touched it in a decade, but I have started playing with Zig so this was useful to me. You aren't always the target.
- dmurray 2y agoIt feels a bit performative to me: the article goes out of way not to explain it by giving the C equivalent. Perhaps some day Zig will have replaced C and beginners will come to Zig having never touched C, and in that context this approach makes sense - after all, you wouldn't litter an introductory article on C with comparisons to Algol. But today, surely the modal Zig beginner already knows enough C that the syntax would better be explained by reference to C.
- amjoshuamichael 2y agoYeah I found this article super weird. Explaining pointers & dereferencing is reasonable, but doing it in the context of Zig specifically, like Zig is the first language to feature dereferencing, is odd. Especially since pointers are such a fundamental part of low-level (really, any) programming. Also not sure why it's posted here? Edit: Going through this author's website, it seems like a lot of their posts are about rediscovering low-level programming concepts through Zig. Like this article, where they discover you can't compare strings directly, and you have to use memcmp: https://www.openmymind.net/Switching-On-Strings-In-Zig/ https://www.openmymind.net/Switching-On-Strings-In-Zig/ They claim that they blog because they "find that [they] retain things better when I write about them." No problem with that. Just a little odd to see on the hn front page, I suppose.
- wyldfire 2y ago> rediscovering I think this is just "discovering". While you (and I) probably discovered these things with assembly or C languages, it's perfectly reasonable or even appropriate for newer generations to have these kinds of experiences with Zig or Rust.
- amjoshuamichael 2y agoAbsolutely, like I said, there's no problem with what this person is doing or the way that they're exploring computers, I'm just confused as to why it's being posted here.
- psychoslave 2y agoMaybe the place is not reserved to old grey beard? :)
- Tolexx 2y agoI honestly don't understand his displeasure at the article being posted here. It reeks of elitism to me.
- FlyingSnake 2y agoFTA: “power.* is how we dereference a pointer“ This Is basically the gist of the article. I’m surprised to see that so many programmers these days don’t know C and basic pointers.
- dazed_confused 2y agoAre you honestly surprised?
- epolanski 2y agoWhy would you? Large parts of the industry does really work with low(er) level languages. Even people who went through C/C++ in their formal education/start of their career may have not used it for a long time.
- FlyingSnake 2y agoLearning C is a time honored tradition. I’m surprised that I’ve to defend C language on a forum like HN.
- xigoi 2y agoEveryone who knows pointers had to learn them at some point.
- d0mine 2y agoC is not even in the top dozen most popular languages https://www.jetbrains.com/lp/devecosystem-data-playground/ https://www.jetbrains.com/lp/devecosystem-data-playground/
- FlyingSnake 2y agoTreating everything a popularity contest is definitely not the best way, right?
- timewizard 2y agoSo.. is a double dereference.. ptr.*.* ?
- SpaghettiCthulu 2y agoYes
- cassepipe 2y agoYes, but unlike C's terribly confusing "declaration follows usage" style, which no tells you about btw, zig's pointer syntax doesn’t turn into a nightmarish puzzle. In Zig, you can pretty much read the types aloud and it makes, your brain does not need to peek for parsing. For me it's too late, I got used to the C way but I still want the better thing to get adopted. No more int ((foo)(int))[5]; nonsense—just T, [N]T, or *T, making intent crystal clear.
- toasterlovin 2y ago> Yes, but unlike C's terribly confusing "declaration follows usage" style, which no tells you about btw I happen to be reading the K&R C book right now and they do in fact tell you this.
- ajross 2y agoYeah, not sure where that came from. The ANSI C standard was extensively documented in books and articles and specs at all levels of rigor starting from the mid-80's. No one has ever lacked for a reference for how function pointer declaration looks. That said, C's function pointer declaration syntax is indeed awful. But really that's because ANSI took a very hardline "no incompatible changes" tact when adding prototypes to the language, which limited the ways they could express them. That decision is one of the reasons we're still writing C today. Any yahoo can come up with a new language, kids do it all the time. ANSI's job was to add features to the language in which Unix was already written.
- cassepipe 2y agoWell it's been lost on every C online tutorial I guess I have not read it so that's on me I guess
- silisili 2y agoI wonder why they went that route. At this point in my career the first notation is ingrained in my head. The bottom looks like regex.