C中的Const返回类型
我正在阅读一些代码示例,他们返回了一个const int。 当我尝试编译示例代码时,我遇到了有关冲突返回类型的错误。 所以我开始搜索,认为const是问题(当我删除它时,代码工作正常,不仅编译,而且按预期工作)。 但我从来没有能够找到特定于const返回类型的信息(我为结构/参数/等等做了,但没有返回类型)。 所以我尝试编写一段代码来简单地展示const可以做什么。 我想出了这个:
#include int main() { printf("%i", method()); } const int method() { return 5; }
当我编译这个时,我得到:
$ gcc first.c first.c:7: error: conflicting types for 'method' first.c:4: note: previous implicit declaration of 'method' was here
但是,每当我删除const时,它就像预期的那样,只打印出一个5,一个继续生命。 所以,任何人都可以告诉我当用作返回类型时const应该是什么意思。 谢谢。
在调用之前添加method()的原型将修复错误。
const int method(); int main() { printf("%i", method()); }
Line 7: error: conflicting types for 'method'
这个错误告诉我们, method()
是由编译器创建的(因为它找不到它),返回类型不同于const int
(可能是int)。
Line 4: error: previous implicit declaration of 'method' was here
这个其他错误告诉我们实际上编译器创建了自己的method
版本。
const
对返回值没有意义,因为返回值在任何情况下都是rvalues ,并且无法修改。 你得到的错误是因为你在声明之前使用了一个函数,所以隐式假设它返回int
,而不是const int
但是当实际定义了方法时,返回类型与原始的asssumption不匹配。 如果它返回double
而不是int
,你会得到完全相同的错误。
例如:
#include int main() { printf("%i", method()); } double method() { return 5; }
产生:
$ gcc -std=c99 -Wall -Wextra -pedantic impl.c impl.c: In function 'main': impl.c:4: warning: implicit declaration of function 'method' impl.c: At top level: impl.c:7: error: conflicting types for 'method' impl.c:4: note: previous implicit declaration of 'method' was here
看看提高警告级别有多大帮助!
在你告诉C足够多的函数 – 它的名字,返回类型,const-ness和参数之前,C对你使用函数的返回类型进行猜测。 如果这些猜测是错误的,你就会得到错误。 在这种情况下,他们是错的。 使用原型或移动呼叫上方的function。
哦,关于CONST-ness:这意味着如果用相同的参数再次调用它,函数的值将是相同的,并且应该没有(重要的)副作用。 这对于优化是有用的,并且它还使纪录片声明编译器可以强制执行有关参数。 函数承诺不会改变常量,编译器可以帮助防止它。
您发布的代码应该至少为您提供一个未定义的标识符: method
。 在调用函数之前,您需要在范围内声明。 更好用:
#include const int method() { return 5; } int main() { printf("%i", method()); }
定义也是一种声明。 所以,这应该可以解决你的错误。
main
看到没有原型的method()
的使用,所以假设它返回int。 然后将其声明为返回const int
。 在main
之前移动method()
的声明,或者在main
之前放置一个原型。