Skip to content

Comment on Source Code Typography

Comments

I come from a photography and design background, and I've tended to naturally write code much like the author is suggesting.

However, the for loop is mystifying to me, but I don't fully understand the actual code there. Would anyone care to explain it?

Well, I guess you expect that it is copying something. It is implemented using C pointers, which enjoy a reputation of being difficult to explain. For example:

http://stackoverflow.com/questions/15151377/what-exactly-is-...

Accepting some level of fuzziness, the ++ parts are moving through two spots in memory, the * parts are copying the contents of the one to the other. It all goes 1 byte at a time.

(I apologize if my assumption that you are not familiar with C is off base)

    for (; (*to = *from) != 0; ++from, ++to)
to and from are pointers to characters. When we increment them, we point to the next memory location in each string.
    "hello"  // a sequence of bytes with a zero marking the end 
     ^-- to
In our loop, we don't need to allocate any helper variables, and can just increment our pointers to point to the next memory slot in each string. I'm not a C expert, so I may get this subtly wrong, but I believe this is equivalent to:
    do {
        *to = *from;    // copy character from source to destination
    } while (0 != *to); // until we reach the '\0' terminator
AboutSource Built by g1lg1l

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