C中的Const返回类型

Lei*_*sen 4 c const

我正在阅读一些代码示例,并返回了一个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)

看看提高警告级别有多大帮助!


Ian*_*Ian 5

在你告诉C足够的函数 - 它的名字,返回类型,const-ness和参数之前,C对你使用函数的返回类型进行猜测.如果这些猜测是错误的,那么你会得到错误.在这种情况下,他们是错的.使用原型或移动呼叫上方的功能.

哦,关于CONST-ness: 这意味着如果用相同的参数再次调用它,函数的值将是相同的,并且应该没有(重要的)副作用.这对于优化是有用的,并且它还使纪录片声称编译器可以强制执行有关参数.函数承诺不会改变常量,编译器可以帮助防止它.

  • +1表示返回值的真正`const`解释.你应该提到在使用gcc时最好使用`__attribute __((const))`和`__attribute __((pure))`.它更明确. (4认同)
  • 你能否提供一个参考,表明const限定返回类型意味着一个函数具有纯行为,它为相同的输入值产生相同的返回值?我从来没有听说过这个. (2认同)
  • http://www.ohse.de/uwe/articles/gcc-attributes.html#func-const不可否认,这是GNU文档而不是标准,但它应该让你去.我在Windows强制要求之前从Borland的C++编译器附带的书中学到了这一点. (2认同)
  • 这是不同的东西,甚至那个页面最后都是错的.该语言指定在函数类型*上不应指定`const`*.该语言完全允许它返回类型.该页面的示例将其应用于函数类型(即函数的类型,*而不是*类型的返回类型,如最后的文本声明).更具体地说,C呈现它未定义的行为,而C++完全禁止它,尽管C++ 0x放宽了规则并且说`const`被忽略了. (2认同)

Luc*_*eis 4

在调用 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.

  • 应该是: const int method(void); 而不是 const int method(); ? (5认同)
  • 您在调用之前尚未添加任何原型。这是一个没有原型的声明。 (2认同)