我正在阅读一些代码示例,并返回了一个const int.当我尝试编译示例代码时,我遇到了有关冲突返回类型的错误.所以我开始搜索,认为const是问题(当我删除它时,代码工作正常,不仅编译,而且按预期工作).但我从来没有能够找到特定于const返回类型的信息(我为结构/参数/等等做了,但没有返回类型).所以我尝试编写一段代码来简单地展示const可以做什么.我想出了这个:
#include <stdio.h>
int main() {
printf("%i", method());
}
const int method() {
return 5;
}
Run Code Online (Sandbox Code Playgroud)
当我编译这个时,我得到:
$ gcc first.c
first.c:7: error: conflicting types for ‘method’
first.c:4: note: previous implicit declaration of ‘method’ was here
Run Code Online (Sandbox Code Playgroud)
但是,每当我删除const时,它就像预期的那样,只打印出一个5,一个继续生命.所以,任何人都可以告诉我当用作返回类型时const应该是什么意思.谢谢.
CB *_*ley 23
const对返回值没有意义,因为返回值在任何情况下都是rvalues,并且无法修改.您获得的错误来自于在声明函数之前使用函数,因此隐式假定它返回int,而不是const int在实际定义方法时,返回类型与原始asssumption不匹配.如果是,那么你会得到完全相同的错误double而不是int.
例如:
#include <stdio.h>
int main() {
printf("%i", method());
}
double method() {
return 5;
}
Run Code Online (Sandbox Code Playgroud)
产生:
$ 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
Run Code Online (Sandbox Code Playgroud)
看看提高警告级别有多大帮助!
在你告诉C足够的函数 - 它的名字,返回类型,const-ness和参数之前,C对你使用函数的返回类型进行猜测.如果这些猜测是错误的,那么你会得到错误.在这种情况下,他们是错的.使用原型或移动呼叫上方的功能.
哦,关于CONST-ness: 这意味着如果用相同的参数再次调用它,函数的值将是相同的,并且应该没有(重要的)副作用.这对于优化是有用的,并且它还使纪录片声称编译器可以强制执行有关参数.函数承诺不会改变常量,编译器可以帮助防止它.
在调用 method() 之前添加 method() 的原型将修复该错误。
const int method();
int main() {
printf("%i", method());
}
Run Code Online (Sandbox Code Playgroud)
Line 7: error: conflicting types for 'method'
Run Code Online (Sandbox Code Playgroud)
这个错误告诉我们,它method()是由编译器创建的(因为它没有找到它),其返回类型与const int(可能是 int)不同。
Line 4: error: previous implicit declaration of 'method' was here
Run Code Online (Sandbox Code Playgroud)
这个另一个错误告诉我们,实际上编译器创建了自己的method.