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
广告