Kai*_*ain 6 c constants function
我有一段这样的代码:
#include <stdio.h>
int add(const int x, const int y);
int main()
{
printf("%d", add(9, 8));
return 0;
}
int add(int x, int y)
{
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
我在没有 const 参数的情况下定义了它之后,使用 const 参数向前声明了函数“add”,并且当我编译它时,编译器没有给出任何抱怨。
程序的输出是: 17. 为什么会发生这种情况?
嗯,函数声明和函数定义必须兼容,我们都知道。所以相同的名称和相同的返回类型和参数类型。所以我们从C11 6.7.6.3p15得知:
为了使两个函数类型兼容,相应的参数应具有兼容的类型。[...]
但是,该文本后面有一个明确的后门:
(在确定类型兼容性时 [...] 使用限定类型声明的每个参数都被视为具有其声明类型的非限定版本。)
类型限定符例如是const。并且它被忽略了。您可以放置任何类型限定符,在检查函数声明是否彼此相同时,它会被忽略。
int func(int n);
int func(volatile int n);
int func(const int n);
int func(const volatile int n);
int func(int n) {
return n;
}
Run Code Online (Sandbox Code Playgroud)