const指標的一些總結

來源:互聯網
上載者:User
前兩天在網上看到華為的一些筆試題,對基礎的掌握仍然是這種大公司所重視的。其間對指標掌握的要求比較多,有一道是關於const指標的。看到那道題,回來整理了一些有關const指標的內容,分享一下。

  const說明指標變數,組合的情況可能會顯得很複雜。使用指標時要涉及兩個目標,即指標本身和指標所指的對象。關於const指標變數,可歸結為以下三種:
  1.指向常量的指標變數;
  2.常指標變數;
  3.指向常量的常指標變數。
  下面來分別談談這三種情況。

一、指向常量的指標變數:
聲明格式: const type * var_name;
或 type const * var_name;
特點: 可改值。
  將指標聲明冠以const,使指向的對象為常量,而不是指標為常量。注意:指向常量的指標不一定指向真正的常量,它也可以指向常量,只是從該指標的角度來看,它所指向的對象是常量,通過該指標不能修改它指向的對象。它還可以指向其它的對象,可以不初始化。
-----eg:
int a = 0,b = 1;
const int c = 3;
const int* pi; //等同於 (const int*) pi;
pi = &a;
*pi = 10; //錯誤:不能修改它指向的對象。
a = 10;
pi = &b;
*pi = &b;
*pi = 20; //錯誤:不能修改它指向的對象。
b = 20;
pi = &c;
*pi = &c;
*pi = 30; //錯誤:不能修改它指向的對象。
-----eg2:
const char* pc = "asdf";
pc[3] = 'a'; //錯誤:不能修改它指向的對象。
pc = "ghik";
-----eg3:
const char* step[3] =
{"left","right","hop"};
step[2] = "skip";
step[2][1] = 'i'; //錯誤:不能修改它指向的對象。

二、常指標常量:
聲明格式: type* const var_name;
特點: 可改對象。
  要把指標本身,而不是它指向的對象聲明為常量,採用運算子 *const,必須初始化,通過該指標可以修改它指向的對象,但它不可以指向其他的對象。
-----eg:
int a = 0,b = 1;
int* const pi = &a; //等於 int* (const pi) = &a;
*pi = 10;
pi = &b; //錯誤:pi本身為常量,不能指向其他對象。

三、指向常量的常指標變數:
聲明格式: const type * const var_name;
特點: 值與對象均不能改。
  要使兩個目標都是常量,兩者都要聲明為 const 。
eg:
int a = 0,b = 1;
const int c = 3;
const int* const pi = &a; //相當於: (const int*)(const pi) = &a;
*pi = 10; //錯誤:不能修改它的對象。
a = 10;
pi = &b; //錯誤:不能指向其它對象。
eg2:
const char* const pc = "asdf";
pc[3] = 'a'; //錯誤:不能修改它的對象。
pc = "ghik"; //錯誤:不能指向其它對象。
eg3:
const char* const step[3] =
{"left","right","hop"};
step[2] = "skip"; //錯誤:不能指向其它對象。
step[2][1] = 'i'; //錯誤:不能修改它的對象。

  一般的,當聲明中出現 const 描述符時,它修飾的是緊跟其後的聲明元素或者在 const 成員函式宣告中函數的 this 指標。
  注意:可以將變數的地址賦給指向常量的指標變數,不會因此有什麼害處,但是,常量的地址不能賦給無約束的指標。
eg:
int a = 1;
const int c = 2;
const int* p1 = &c;
const int* p2 = &a;
int* p3 = &c; //非法!
int* const p4 = &c; //非法! 指標常量 p4 能夠改值。
const int* const p5 = &c;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.