Given the following C source code:
const int foo(void)
{
return 42;
}
gcc compiles without errors, but with -Wextra or -Wignored-qualifiers, the following warning appears:
warning: type qualifiers ignored on function return type
I understand that there’s good reason in C++ to distinguish between const functions and non-const functions, e.g. in the context of operator overloading.
In plain C however, I fail to see why gcc doesn’t emit an error, or more concisely, why the standard allows const functions.
Why is it allowed to use type qualifiers on function return types?
Consider:
If
constwere not permitted on the return value then the code would compile (and cause undefined behaviour at runtime).constis useful when a function returns a pointer to something unmodifiable.