Skip to content

Comment on Source Code Typographyparent

Comments

Maybe the reason "C-hackers" do it that way is because it actually works, while your example completely fails to null-terminate the destination string.

Good point. I guess it gets a bit more complicated when you try to do the right thing. So I'll re-examine the simple while loop like oneeyedpigeon posted:

  while (*t++ = *f++)
      ;
This code really packs a lot of punch. The value of f is copied to t and then both pointers are incremented. If the value is 0 the loop is terminated. So there's always at least one character copied.

In my initial rash response the loop would exit without copying the 0. So to fix it I might just add a new line

  *to = 0;
(if I'm not mistaken the pointer is already incremented when the loop exits).

Another option would be a while loop with a break statement, It looks weird, but does express the correct intent, which is "continuously copy from source string and exit if you've reached the end":

  while (true) {

    *to = *from;
    if (*to == 0) break;

    from++
    to++;

  }
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.