#include <iostream>
usingnamespace std;
constchar * function()
{
return"some Text";
}
constint function1()
{
return 1;
}
int main()
{
char * h = function(); //1 does not compile
int h = function1(); //2 works
return 0;
}
My question:
Why does the program compile if I comment out the line marked 1 but it does not compile if I comment out the line marked 2? What is the sense of const in function1?
I'm not fully sure, but maybe one or more of the reasons why the conversion from const char* to char * has been deprecated have something to do with it...
function returns a pointer to const char* and you can't just assign it to a pointer to non-const char (without const_cast, anyway). These are incompatible types.
function1 is different, it returns a constant int. The const keyword is rather useless here - you can't change the returned value anyway. The value is copied (copying doesn't modify the original value) and assigned to h.
For function to be analogue to function1, you need to write char* const function(), which will compile just fine. It returns a constant pointer (as opposed to a non-const pointer to a const type).