Snis Pilbor said:
Boy am I glad I don't work under you, since you seem to think you're
the sole arbiter of good design.
Yes, MQ is the sole arbiter of good design. So am I. So are you.
}
MQ makes a valid point; there are definite drawbacks to that
particular design (returning a pointer to a static buffer). Note that
there are functions in the C standard library that do exactly this,
such asctime() and ctime() -- which means you have to be very careful
in how you use them.
There's a big difference between expression an opinion about something
and claiming that your own opinion is the ultimate truth. MQ merely
did the former; you're reacting as if he'd done the latter.
[...]
If I wanted a language which was always like "Hey! That's, um...
questionable, because you might not know what you're doing... so um,
it's forbidden!" then I would switch to Java.
Nobody suggested forbidding anything.
Also the fact you suggested returning a pointer to static memory might
be undefined behavior, is extremely misleading and probably adds new
lots of new confusion to anyone who hasn't been doing C long enough to
immediately see it as the nonsense it is.
It was a mistake. Mistakes can easily be corrected by posting the
correct information (in this case, returning a pointer to static data
doesn't invoke undefined behavior, though it can lead to it, or to
other bad outcomes, if you're not careful).
Another approach I've used in the past is to declare a static array of
strings within a function (actually a 2-dimensional array of char),
and a static integer index that specifies which one to use next. The
function, which returns a char*, initializes the string indicated by
the current index and returns a pointer to it while incrementing the
index for next time, resetting it to 0 when it goes past the end of
the array. With, say, half a dozen or so such rotating buffers, you
can do things like:
printf("%s %s %s %s\n", func(1), func(2), func(3), func(4));
without requiring the caller to worry about where to store the result.
It's not a perfectly clean solution, but it can be useful sometimes
(and, of course, you *still* have to be careful not to retain more
than N results).