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?
In the C, C++, and D programming languages, a type qualifier is a keyword that is applied to a type, resulting in a qualified type. For example, const int is a qualified type representing a constant integer, while int is the corresponding unqualified type, simply an integer.
A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether: The value of an object can be changed. The value of an object must always be read from memory rather than from a register. More than one pointer can access a modifiable memory address.
Consider:
#include <stdio.h>
const char* f()
{
return "hello";
}
int main()
{
const char* c = f();
*(c + 1) = 'a';
return 0;
}
If const
were not permitted on the return value then the code would compile (and cause undefined behaviour at runtime).
const
is useful when a function returns a pointer to something unmodifiable.
It's irrelevant if the value returned from the function is qualified as const
.
You cannot change the value returned even if it wasn't qualified.
foo() = -42; /* impossible to change the returned value */
So using const
is redundant (and normally omitted).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With