我想知道什么是“const”关键字在'C'的函数之前。const关键字在函数之前C
例如:
extern const int func1(int x[], const struct dummy_s* dummy)
在此先感谢
我想知道什么是“const”关键字在'C'的函数之前。const关键字在函数之前C
例如:
extern const int func1(int x[], const struct dummy_s* dummy)
在此先感谢
如果打开警告时,将有两个:
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允许隐式返回类型int时有效,如果没有明确指定返回类型。但在任何情况下,返回值都不是左值,不能改变。所以const修饰符是多余的。
在标准C中,你的代码不会被编译。您不允许省略C函数的返回类型。
在被称为C90的旧版C中,允许您省略返回类型,在这种情况下,它将默认为int。在老版本的C,你的代码就等于:
extern const int func1(int x[], const struct dummy_s* dummy);
下一个问题然后,它曾经是有意义的从一个函数返回const int
,而不是仅仅int
?不,它不...因为返回的变量总是放在堆栈上的硬拷贝。它不是一个左值,并且函数在运行时无论如何都被执行,没有理由为什么这个值需要是const。
可能重复[什么是const指针?](http://stackoverflow.com/questions/7715371/whats-the-point-of-const-pointers) – Coconop 2014-10-17 13:37:40
@Coconop:我认为他的意思是第一个'const'? – 2014-10-17 13:38:20
糟糕,为mods sry。这太糟糕了,我无法撤销这一点。 – Coconop 2014-10-17 13:41:34