Robert P. J. Day wrote: > i'm about to design and implement a number of routines that return > strings and, as far as i can tell, i have two general design choices. > > int func(char* buf, int bufsiz) ; > char* func() ; > > that first form obviously accepts the address of a buffer (and its > size) into which to copy the result, and leaves the "int" return value > to be used perhaps as an error code. perfectly reasonable, but it > forces every invocation to first have a buffer ready to go. > > the second form would be intuitively more natural, but is affected > by the scope of the result. the approach i would use there might be: > > char* > func() > { > static buf[128] ; // or whatever size is appropriate > ... copy result into buf ... > return buf ; > } > > an error of some kind might be implemented by returning NULL, but that > will restrict the range of error codes i can pass back. > > are there compelling arguments either way? while i like the natural > feel of the second form, i have to admit the first form is more > informative. thoughts? Avoid the second form. Apart from not being re-entrant, it can lead to bugs which can be hard to find, particularly if the function in question is relatively general-purpose and may be used from various places in your code. The first form should be used whenever you can determine in advance a reasonable size for the buffer. Otherwise, use malloc(). -- Glynn Clements <glynn@xxxxxxxxxxxxxxxxxx> - : send the line "unsubscribe linux-c-programming" in the body of a message to majordomo@xxxxxxxxxxxxxxx More majordomo info at http://vger.kernel.org/majordomo-info.html