:: Re: [DNG] "Common knowledge?"-quest…
Etusivu
Poista viesti
Vastaa
Lähettäjä: Hendrik Boom
Päiväys:  
Vastaanottaja: dng
Aihe: Re: [DNG] "Common knowledge?"-question
On Sat, Jan 23, 2016 at 11:45:30AM -0500, Steve Litt wrote:
> 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.


A good compiler would inline it even if you write it as a funciton,
because it's not recursive, and its code is probably smaller than that
of a function call.

The trouble with macros in C is that they do not respect nested scopes.
(This is a criticism of the language, not of coding style.)

-- hendrik
k