gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:23:03 25 4
gpt4 key购买 nike

给定以下 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 函数。

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

最佳答案

考虑:

#include <stdio.h>

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

*(c + 1) = 'a';

return 0;
}

如果 const 不允许出现在返回值中,那么 code会编译(并在运行时导致未定义的行为)。

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

关于c - 函数返回类型的类型限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12052468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com