Classifiers by function return type

Given the following C source code:

const int foo(void)
{
    return 42;
}

gcccompiles without errors, but with -Wextraor -Wignored-qualifiersthe following warning appears:

warning: type qualifiers ignored on function return type

I understand that in C ++ there is a good reason to distinguish between functions constand not functions const, for example. in the context of operator overloading.

In simple C, however, I do not understand why it gccdoes not emit an error, or more briefly, why the standard allows functions const.

Why are type qualifiers allowed to return function types?

+5
source share
3 answers

Consider:

#include <stdio.h>

const char* f()
{
    return "hello";
}
int main()
{
    const char* c = f();

    *(c + 1) = 'a';

    return 0;
}

const , code ( undefined ).

const , - .

+2

, , , const.

, .

foo() = -42; /* impossible to change the returned value */

, const ( ).

+2

, , , , const non-pointer return.

Also, your comparison with C ++ does not work a bit, since the constant method in C ++ is declared using constlast:

int foo() const;

There is no connection between a method constand a method that has a return value const; these are completely different things. The syntax makes this clear enough.

+2
source

All Articles