gpt4 book ai didi

C 中的 Const 返回类型

转载 作者:太空狗 更新时间:2023-10-29 15:09:26 25 4
gpt4 key购买 nike

我正在阅读一些代码示例,它们返回了一个 const int。当我尝试编译示例代码时,我遇到了有关返回类型冲突的错误。所以我开始搜索,认为 const 是问题所在(当我删除它时,代码工作正常,不仅编译成功,而且按预期工作)。但是我从来没有能够找到专门与 const 返回类型相关的信息(我为结构/参数/等找到了信息,但没有找到返回类型)。所以我尝试编写一段代码来简单地展示 const 可能做什么。我想到了这个:

#include <stdio.h>

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,a 继续存在。那么,谁能告诉我 const 用作返回类型时的含义。谢谢。

最佳答案

const 对返回值没有意义,因为返回值在任何情况下都是右值 并且无法修改。你得到的错误是因为你在函数被声明之前使用它,所以它被隐式地假设返回 int,而不是 const int 但是当方法实际上定义了,返回类型与原来的假设不符。如果返回 double 而不是 int,您会得到完全相同的错误。

例如:

#include <stdio.h>

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 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541766/

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