Reputation: 5917
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?
Upvotes: 7
Views: 10712
Reputation: 399813
Because it makes sense for pointer types, my guess is that it simply keeps the grammar simpler, so nobody thinks it's worth making const
non-pointer return values be an error.
Also, your comparison with C++ is a bit off, since a constant method in C++ is declared by having const
last:
int foo() const;
There is no relationship between a method being const
, and a method having a const
return value, they are completely distinct things. The syntax makes this fairly clear.
Upvotes: 2
Reputation: 121971
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.
Upvotes: 3
Reputation: 108978
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).
Upvotes: 1