2014-10-17 122 views
-1

我想知道什么是“const”关键字在'C'的函数之前。const关键字在函数之前C

例如:

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

在此先感谢

+0

可能重复[什么是const指针?](http://stackoverflow.com/questions/7715371/whats-the-point-of-const-pointers) – Coconop 2014-10-17 13:37:40

+2

@Coconop:我认为他的意思是第一个'const'? – 2014-10-17 13:38:20

+0

糟糕,为mods sry。这太糟糕了,我无法撤销这一点。 – Coconop 2014-10-17 13:41:34

回答

4

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

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) 
+0

不要只是打开你的警告,编译你的C代码为标准C.'gcc -std = c11 -pedantic-errors -Wall -Wextra'。你现在会得到错误,而不仅仅是警告。 – Lundin 2014-10-17 14:26:57

+0

@Lundin完全取决于用户使用哪种标准。如果他们使用C89,它应该是完全有效的代码。你不能假设自2011年以来每个程序都已经完成:) – Vality 2014-10-17 14:57:33

2

它没有任何意义。看起来,这是一些旧的代码,当C允许隐式返回类型int时有效,如果没有明确指定返回类型。但在任何情况下,返回值都不是左值,不能改变。所以const修饰符是多余的。

2

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

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

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

下一个问题然后,它曾经是有意义的从一个函数返回const int,而不是仅仅int?不,它不...因为返回的变量总是放在堆栈上的硬拷贝。它不是一个左值,并且函数在运行时无论如何都被执行,没有理由为什么这个值需要是const。

+0

“你总是可以给非常量变量赋一个非常量变量” - 你的意思是_from_常量,我想。 – davmac 2014-10-17 14:28:14

+0

@davmac试图澄清一点。 – Lundin 2014-10-17 14:37:32