给出以下C源代码:
const int foo(void)
{
return 42;
}
gcc
编译时没有错误,但是-Wextra
或-Wignored-qualifiers
会出现以下警告:
warning: type qualifiers ignored on function return type
我理解在C ++中有充分理由区分const
函数和非const
函数,例如在运算符重载的上下文中。
在普通的C中,我不明白为什么gcc
不会发出错误,或者更简洁,为什么标准允许const
函数。
为什么允许在函数返回类型上使用类型限定符?
答案 0 :(得分:2)
如果从函数返回的值被限定为const
,则无关紧要。
即使没有合格,也无法更改返回的值。
foo() = -42; /* impossible to change the returned value */
因此使用const
是多余的(通常省略)。
答案 1 :(得分:2)
考虑:
#include <stdio.h>
const char* f()
{
return "hello";
}
int main()
{
const char* c = f();
*(c + 1) = 'a';
return 0;
}
如果返回值不允许const
,则code将编译(并在运行时导致未定义的行为)。
const
很有用。
答案 2 :(得分:2)
因为它对指针类型有意义,我的猜测是它只是简化了语法,所以没有人认为值const
非指针返回值是错误的。
此外,您与C ++的比较有点偏,因为C ++中的常量方法是通过const
最后声明的:
int foo() const;
作为const
的方法与具有const
返回值的方法之间没有关系,它们是完全不同的东西。语法使这一点相当清楚。