给出以下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
函数.
为什么允许在函数返回类型上使用类型限定符?
考虑:
#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
当函数返回指向不可修改的内容的指针时很有用。
归档时间: |
|
查看次数: |
9273 次 |
最近记录: |