当编译器确定函数类型时,参数的高级限定符将被丢弃。
所以这两个函数声明
int fputc(int c, FILE *stream);
int fputc( const int c, FILE *stream);
声明同一个函数。
还有这两个函数声明
int fputs(const char *s, FILE *stream);
int fputs(const char * const s, FILE *stream);
同样声明一个函数。
所以高级限定符 const 的意义不是针对函数的用户,而只是针对函数的内部定义。在任何情况下,相应的参数都是按值传递的,该函数处理参数的副本。因此,在函数内部,副本是否具有限定符 const 与函数的用户无关。
考虑以下演示程序
#include <stdio.h>
void f( const int x );
void f( int x )
{
x += 10;
printf( "Inside the function x = %d\n", x );
}
int main( void )
{
int x = 1;
printf( "Before calling f x = %d\n", x );
f( x );
printf( "After calling f x = %d\n", x );
}
它的输出是
Before calling f x = 1
Inside the function x = 11
After calling f x = 1
所以对于函数的用户来说,函数的参数x是否有限定符const并不重要。从编译器(和函数的用户)的角度来看,这两个声明都声明了同一个函数。
函数参数是它们的局部变量。并且用户不用担心函数中是否会使用限定符 const 声明某些局部变量。
请注意此声明中的内容
int fputs(const char *s, FILE *stream);
它不是第一个声明为常量的参数。指针指向的数据是常量。
但是在这个声明中
int fputc( const int c, FILE *stream);
参数本身就是常数。