:: Re: [DNG] "Common knowledge?"-quest…
Top Page
Delete this message
Reply to this message
Author: Steve Litt
Date:  
To: dng
Subject: Re: [DNG] "Common knowledge?"-question
On Fri, 22 Jan 2016 21:34:28 +0000
Rainer Weikusat <rainerweikusat@???> wrote:

> Can the effect of the following C function
>
> static void print_start(char const *name, char const *what)
> {
>     char *buf, *p;
>     unsigned name_len, what_len, total;

>
>     name_len = strlen(name);
>     what_len = strlen(what);
>     total = name_len + what_len + 3;

>
>     p = buf = alloca(total);
>     memcpy(p, name, name_len);
>     p += name_len;
>     *p++ = ' ';
>     memcpy(p, what, what_len);
>     p += what_len;
>     *p++ = ':';
>     *p = ' ';

>
>     *buf &= ~0x20;

>
>     Write(2, buf, total);
> }

>
> be considered obvious or should it rather get an explanation?


Hi Rainer,

Others have pointed out potential coding problems, but I'm just going
to answer your question about need for comments. In my opinion, the
preceding function is short enough to document itself *if and only if*
the function gets a much more descriptive name. Descriptive of what it
does and how it's used.

print_start() means nothing to me. Is "start" a noun (the start of the
record) or a verb (start the printing). And the print isn't to a
printer, it's to stdout, so a better word would be "output". But even
those aren't sufficient: This thing is concatenating two strings,
adding punctuation, and capitalizing the first character. Why are all
these things necessary? If the function name can address that, perhaps
it can be self documenting.

Otherwise, there's no shame in putting a few lines of comments above
the function, and personally I'd put an inline comment on that *buf &=
~0x20; trick. Or you could make a macro called upcase_first_letter()
that does that. That makes it self-documenting, and yet because it's a
macro it compiles as if it were inline.

SteveT

Steve Litt
January 2016 featured book: Twenty Eight Tales of Troubleshooting
http://www.troubleshooters.com/28