【问题标题】:const keyword before a function in CC中函数前的const关键字
【发布时间】:2014-10-17 13:36:24
【问题描述】:

我想知道 'C' 中函数之前的“const”关键字的作用。

例如:

extern const int func1(int x[], const struct dummy_s* dummy)

提前致谢

【问题讨论】:

  • @Cocoop: 我想他的意思是第一个const
  • 哎呀,为模组道歉。太糟糕了,我无法撤消此操作。
  • @JohnnyMopp; C++ != C.
  • 类型丢失了,所以这肯定是你在某个地方找到的,你能给出确切的行吗?

标签: c


【解决方案1】:

如果您打开警告,您将有两个:

warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
warning: 'const' type qualifier on return type has no effect [-Wignored-qualifiers]

这很容易让您得出以下结论:

extern const func1(int x[], const struct dummy_s* dummy)

基本相同:

extern int func1(int x[], const struct dummy_s* dummy)

【讨论】:

  • 不要只打开警告,将 C 代码编译为标准 C。gcc -std=c11 -pedantic-errors -Wall -Wextra。您现在将收到错误,而不仅仅是警告。
  • @Lundin 完全取决于用户使用的标准。如果他们使用 C89,它应该是完全有效的代码。你不能假设每个程序都是从 2011 年开始制作的 :)
【解决方案2】:

没有任何意义。如果未明确指定返回类型,则似乎是一些旧代码在 C 允许隐式返回类型 int 时有效。但在任何情况下,返回值都不是左值,无法更改。所以 const 限定符是多余的。

【讨论】:

    【解决方案3】:

    在标准 C 中,您的代码将无法编译。不允许省略 C 函数的返回类型。

    在称为 C90 的旧版 C 中,您可以省略返回类型,在这种情况下,它将默认为 int。在旧版本的 C 中,您的代码将等于:

    extern const int func1(int x[], const struct dummy_s* dummy);
    

    接下来的问题是,从函数返回 const int 而不仅仅是 int 是否有意义?不,它不会……因为返回的变量始终是放在堆栈上的硬拷贝。它不是左值,而且函数是在运行时执行的,没有理由为什么这个值需要是 const。

    【讨论】:

    • “你总是可以将一个非 const 变量分配给一个 const 变量”——我认为你的意思是 from 一个 const 变量。
    • @davmac 试图澄清一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多