函数返回类型的类型限定符

Phi*_*lip 6 c

给出以下C源代码:

const int foo(void)
{
    return 42;
}
Run Code Online (Sandbox Code Playgroud)

gcc编译没有错误,但有-Wextra-Wignored-qualifiers,出现以下警告:

warning: type qualifiers ignored on function return type
Run Code Online (Sandbox Code Playgroud)

我理解在C++中有很好的理由来区分const函数和非const函数,例如在运算符重载的上下文中.

然而,在普通的C中,我没有看到为什么gcc不发出错误,或者更简洁地说明为什么标准允许const函数.

为什么允许在函数返回类型上使用类型限定符?

hmj*_*mjd 4

考虑:

#include <stdio.h>

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

    *(c + 1) = 'a';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果const返回值不允许,则代码将编译(并在运行时导致未定义的行为)。

const当函数返回指向不可修改的内容的指针时很有用。