Manohar
Manohar

Reputation: 3975

returning const char * from a function in C

In my library I have to return a string to the callers. The string I am returning will be a global array, the intended use from the caller is just to read the string. I don't want them to modify it..

Is this the right way to declare the function..

const char * get_some_details();

This should generate a warning (tried only gcc) either when the caller assigns the return value to a char * ptr or assigns to const char * ptr, but later tries to modify it.

I am asking because I would expect functions like getenv() to return const char *. But it returns char *. Is there any gotcha in returning const char * ?

Upvotes: 3

Views: 1994

Answers (2)

zwol
zwol

Reputation: 140540

That is the right way to do it.

Many standard library functions take or return char * when logically it should be const char *, for historical reasons: pre-C89, there was no const; post-C89, their type signatures could not be changed without breaking application code. As a general rule, do not use the standard library as a style guide; it is very old and contains many things that are no longer considered good practice. (cough gets)

Upvotes: 2

NPE
NPE

Reputation: 500237

Returning const char* is exactly the right thing to do in these circumstances.

Many older APIs don't use const since they pre-date the introduction of const in C90 (there was no const before then).

Upvotes: 6

Related Questions