C中的常量返回类型 [英] Const return types in C
问题描述
我正在阅读一些代码示例,他们返回了const int。当我尝试编译示例代码时,遇到关于返回类型冲突的错误。因此,我开始搜索,认为const是问题所在(当我删除它时,代码可以正常工作,不仅可以编译,而且可以按预期工作)。但是我永远无法找到专门与const返回类型有关的信息(我对结构/参数/等等等,但是没有返回类型)。因此,我尝试编写一段代码来简单地展示const可以做什么。我想出了这个:
I was reading some samples of code, and they returned a const int. When I tried to compile the examples code I got errors concerning conflicting return types. So I started searching, thinking that the const was the problem (when I removed it, the code worked fine, not only did it compile, but worked as expected). But I never was able to find information specifically pertaining to a const return type (I did for structures/parameters/etc. etc., but not return types). So I tried writing a piece of code to simply show what const may do. I came up with this:
#include <stdio.h>
int main() {
printf("%i", method());
}
const int method() {
return 5;
}
当我对此进行编译时,我得到:
And when I compile this, I get:
$ 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作为返回类型的含义。谢谢。
However, whenever I remove the const, it, as expected, simply prints out a 5, a continues on with life. So, can anyone tell me what const is supposed to mean when used as a return type. Thank you.
推荐答案
在调用method()之前添加其原型将解决该错误。
Adding the prototype of method() before you call it will fix the error.
const int method();
int main() {
printf("%i", method());
}
Line 7: error: conflicting types for 'method'
此错误告诉我们 method()
由编译器创建(因为找不到),其返回类型与 const int
不同(可能是int)。
This error tells us that method()
was created by the compiler (because it didn't find it) with a different return type than const int
(probably int).
Line 4: error: previous implicit declaration of 'method' was here
另一个错误告诉我们,实际上编译器创建了自己的版本的方法
。
This other error tells us that in fact the compiler created its own version of method
.
这篇关于C中的常量返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!