views:

97

answers:

3

I was just skimming the C99 standard, looking for something that I don't remeber now, when I noticed that the pointer returned from the strerror function (section 7.12.6.2) isn't const-qualified, even though the standard says:

The strerror function returns a pointer to the string, the contents of which are
locale-specific. The array pointed to shall not be modified by the program,
but may be overwritten by a subsequent call to the strerror function.

Is there an obvious reason for this function to return a modifiable string instead of something like:

char const * const strerror(int errnum);  

or at the very least

char const * strerror(int errnum);

Thanks.

A: 

This is probably so because many historical implementations use a static buffer into which they "print" the error string.

ninjalj
+4  A: 

Same as for the type of string literals: It was already like that in C89, describing a practice dating back to before the introduction of const in the language. Changing it would make current valid program invalid.

AProgrammer
Yes that makes sense, I had a hunch. Wouldn't a <code>#define const</code> in old implementations of the standard solve that problem though? (I totally get why one wouldn't want to do that, I'm just asking :) )
manneorama
@manneorama: const int foo = 5;
tomlogic
@manneorama, the problem isn't accepting the keyword const in an implementation which would not have it, it is assigning or passing the result of strerror or a string literal to a char*. Retrofitting const correctness is painful as anybody having done that for C++ know.
AProgrammer
+1  A: 

Response about static buffer is wrong; whether the pointer type returned is const or not has nothing to do with the buffer. The return type is completely about API compatibility with historic code which does not use const, and there's no harm in it. Someone writing modern const-aware code will simply use the return value immediately or store it into a pointer-to-const variable.

R..
Reread the question: The array pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the strerror function.
ninjalj
Reread my answer. A static buffer may be used to implement strerror (though this is idiotic since you could just return a pointer to the constant error string in the binary or mmap'd localization file), but whether or not a writable static buffer is used has absolutely nothing to do with the return type of the function. Both const and non-const pointers can point to non-const buffers, and the "right" type to use in this case is const. The only reason for non-const is to cater to legacy const-unaware code that wants to put the result in a non-const pointer variable or function argument.
R..