What behaviour is being caused by the ‘const’ in the following code, in particular, the cast:
const void *foo()
{
void *bar = NULL;
// Assign bar to some address here.
return (const void *)bar;
}
Is the cast necessary? The compiler gives a warning that the type does not match the return type, unless I perform the cast, but is the resultant behaviour any different?
The cast is not required and is even useless. C does not require any warning if you don’t cast.
You can return a
char *when aconst char *return value is expected.This is also true for other types: you can return a
T *when aconst T *is expected.C says that for
returnstatement:You can assign a
char *to aconst char *(note that the opposite is not valid).C says for pointer assignment: