非指针参数(也就是传值参数)不会被修改原始值, const 对它是没有意义的.

const 只用于指针.

1. 第一种用法: const 类型 *变量:

这种用法将限制修改指针指向的值.
#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. 不过也有办法绕过这个限制:
#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. 第二种用法: 类型 *const 变量:

这种用法将限制指针的指向; 下面的例子企图修改指针, 不会成功.
#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;
}


3. 其实不使用 *const, 指针也不会被修改:

还是上面的例子, 去掉 const... 函数也不会成功.

这是为什么呢? 因为指针的本身作为参数时也只是个副本(不过副本指向的值可是真的).
#include <stdio.h>

void swap(int *p1, int *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;
}


4. 但第二种方法不会现在修改指针指向的值:

这也最终可以完成这个 swap 函数; 就这个函数本身来讲, 完全可以不用 const.
#include <stdio.h>

void swap(int *const p1, int *const p2) {
    int t = *p1;
    *p1 = *p2;
    *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;
}


5. 甚至可以两种手段一起上:
#include <stdio.h>

int fun(int const *const p1, int const *const p2) {
    return *p1 + *p2;
}

int main(void)
{
    int x = 111;
    int y = 222;
 
    printf("%d\n", fun(&x, &y));
    
    getchar();
    return 0;
}


posted on 2008-12-04 17:11  万一  阅读(2991)  评论(3编辑  收藏  举报