代码之家  ›  专栏  ›  技术社区  ›  Leif Andersen

C中的Const返回类型

  •  4
  • Leif Andersen  · 技术社区  · 14 年前

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

    然而,每当我删除常量,它,如预期的那样,只是打印出一个5,a继续生活。那么,有人能告诉我const用作返回类型时应该是什么意思吗。非常感谢。

    5 回复  |  直到 14 年前
        1
  •  4
  •   Luca Matteis    14 年前

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

        2
  •  25
  •   CB Bailey    14 年前

    const 因为返回值是 在任何情况下都不能修改。您得到的错误是因为您在函数被声明之前使用了它,因此隐式地假定它返回 int const int 但是,当实际定义方法时,返回类型与原始假设不匹配。如果它返回,你会得到完全相同的错误 double 而不是 内景 .

    例如。:

    #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
    

    看看把警告级别调高是多么有用!

        3
  •  4
  •   dirkgently    14 年前

    method 至少。在调用函数之前,需要在作用域中声明。更好地使用:

    #include <stdio.h>
    
    const int method() {
        return 5;
    }
    
    int main() {
        printf("%i", method());
    }
    

    定义也是声明。所以,这应该可以纠正你的错误。

        4
  •  3
  •   Ian    14 年前

    当你使用一个函数时,C会猜测它的返回类型,在你告诉C足够的函数之前——它的名称、返回类型、常量和参数。如果这些猜测是错误的,你就得到了错误。在这种情况下,他们错了。使用原型或将函数移到调用上方。

    这意味着,如果使用相同的参数再次调用函数,函数的值将是相同的,并且应该没有(重要的)副作用。这对优化很有用,而且它还提出了一个书面声明,即编译器可以强制执行相关参数。函数承诺不改变常量,编译器可以帮助阻止它。

        5
  •  2
  •   Paul Tomblin    14 年前

    main method() 没有原型,所以它假设它返回int。然后您将它声明为返回int const int . 移动声明 方法() 主要的 ,或者在 主要的