const int*、const int * const 和 int const * 在 C 中的區別
指標
在 C 程式語言中,*p 表示儲存在指標中的值,p 表示該值的地址,被稱作指標。
const int* 和 int const* 表示指標可以指向常量 int,由該指標指向的 int 的值不能被更改。但是我們可以更改指標的值,因為指標本身不是常量,它可以指向另一個常量 int。
const int* const 表示指標可以指向常量 int,指標指向的 int 的值不能被更改。而且也不能更改指標的值,因為指標現在是一個常量,它不能指向另一個常量 int。
規則是按從右到左閱讀語法。
// constant pointer to constant int const int * const // pointer to constant int const int *
例子 (C)
取消對註釋掉的錯誤程式碼的註釋並檢視錯誤。
#include <stdio.h>
int main() {
//Example: int const*
//Note: int const* is same as const int*
const int p = 5;
// q is a pointer to const int
int const* q = &p;
//Invalid asssignment
// value of p cannot be changed
// error: assignment of read-only location '*q'
//*q = 7;
const int r = 7;
//q can point to another const int
q = &r;
printf("%d", *q);
//Example: int const* const
int const* const s = &p;
// Invalid asssignment
// value of s cannot be changed
// error: assignment of read-only location '*s'
// *s = 7;
// Invalid asssignment
// s cannot be changed
// error: assignment of read-only variable 's'
// s = &r;
return 0;
}輸出
7
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP