[cairo] return type of cairo_status_to_string ()

Daniel Goldman dagoldman at yahoo.com
Tue Aug 17 19:48:37 PDT 2010


> 

> Daniel Goldman wrote:
> 
> >  I know that the const keyword will not  allow you to assign twice to 
>error_str.
> 
> That is incorrect. You can assign  to error_str many times:
> 
>     const char*  error_str;
>     error_str = "A";
>      error_str = "B";
> 
> What you can't do is assign to what error_str points  at:
> 
>     error_str[0] = 'x'; // will not compile!
>

Oops! You're right. I'm wrong. But who would ever write:

char *error_str;

error_str = cairo_status_to_string (); // Assuming char * return type
error_str [0] = 'x'; // Nobody does this

Every C programming book I've ever read stresses not to do this. Yes, the 
compiler would tell someone who tried to do this. But they are going to make so 
many other mistakes I hardly see how it would matter.

And Joonas' is right that cairo_status_to_string () could allocate memory. But I 
don't see how using "const char *" return type would obviate the need for the 
caller to free the memory. If the called function allocates memory, doesn't it 
need to be freed, no matter what the return type?

Yes, you and Joonas have brought up two possible advantages for "const char *" 
return type. But I think both "advantages" are pretty weak, and the second 
(related to memory allocation) may be non-existent. The advantage of leaving off 
"const" is that const is confusing to many  programmers (apparently including 
myself), and does not fit in as well  with the way that most other functions are 
set up to normally just use  "char *". 


I would say in the real world it would be better to leave off const. I know 
there are many functions that use "const char *", such as strcpy (), strcat (), 
etc. On the other hand, skimming through the back of K+R, I don't see any 
functions with const char * return type. And what about the analogous function 
"char *strerror (int errnum)"? Perhaps you might suggest that strerror () uses a 
static array. But the man page says "This string must not be modified by the 
application". In any case, I think you see my point about "const char *" return 
type being unusual.

Anyway, I at least understand the issue better now. Even if I don't agree with 
the conclusion, it's a pretty minor thing.

Daniel


More information about the cairo mailing list