學點 C 語言(37): 函數 – 常量(const)參數

來源:互聯網
上載者:User
非指標參數(也就是傳值參數)不會被修改原始值, 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;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.