Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning const char * from a function in C

Tags:

c

gcc

constants

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 * ?

like image 307
Manohar Avatar asked Nov 27 '25 19:11

Manohar


1 Answers

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).

like image 98
NPE Avatar answered Nov 29 '25 11:11

NPE