Not sure how much it has to do with optimization. It just might interest the caller whether a function will modify its pointer arguments or not.
That const tells you whether you can pass a string literal (which are unmodifiable) as the second argument. Unfortunately, C allows implicit conversion of const char* to char*, so you could also pass a string literal to an argument that is going to be modified in the function (and probably crash the program doing so), but at least compilers emit warnings if you do that (at least GCC compiling as C++ does).
Code:
#include <ctype.h>
void foo(char* str)
{
str[0] = toupper(str[0]);
}
void bar(const char* str)
{
//str[0] = toupper(str[0]);
}
int main()
{
foo("hello"); //wrong: function is going to attempt to modify a literal
bar("hello"); //safe: function won't modify argument
return 0;
}
What is the benefit? The compiler can optimize by replacing directly the value. For example
That doesn't compile (you are trying to return a non-constant pointer from a constant pointer).
And even then, what is constant is the string pointed to by my. What is not constant is the copy of the pointer itself:
Code:
const char* foo(const char* my)
{
my = "hey"; //my now points to string literal "hey"
return my;
}