Non-pointer parameters (that is, pass-value parameters) are not modified to the original value, and const does not make sense to it.
Const is used only for pointers.
1. The first usage: const type * variable:
This usage restricts the values that the pointer points to.
#include <stdio.h>
int fun(const int *p) {
*p += 1; /* 只有去掉 const 这句才可以执行 */
return *p;
}
int main(void)
{
int num = 3;
printf("%d\n",fun(&num));
getchar();
return 0;
}
2. There are, however, ways to circumvent this limitation:
#include <stdio.h>
int fun(const int *p) {
int *p2 = p; /* 来个重名指针会绕过 const 的限制 */
*p2 += 1;
return *p;
}
int main(void)
{
int num = 3;
printf("%d\n",fun(&num)); /* 4 */
getchar();
return 0;
}
2. Second usage: type *const variable:
This usage will limit the pointing of the pointer; The following example attempts to modify the pointer and will not succeed.
#include <stdio.h>
void swap(int *const p1,int *const p2) {
int *t = p1;
p2 = p1;
p2 = t;
}
int main(void)
{
int x = 111;
int y = 222;
printf("%d,%d\n",x,y);
swap(&x,&y);
printf("%d,%d\n",x,y);
getchar();
return 0;
}