C language const keyword

The key point: const is a modifier. The key is to see where const is modified.
1. const int a
where const modifies int, and int defines an integer value.
Therefore
, the value of the object pointed to by a cannot be passed through *a. Modify, but you can re-assign a to a different object
eg:
const int *a = 0;
const int b = 1;
int c = 1;
a = &b //ok! Extra: Note that the value of b cannot be modified by
a = &c //ok! Extra: Although c itself is not a constant
*a = 2 //erro! The question is here, the value of the object pointed to by a cannot be modified , and the final assignment object is c, so the value of c cannot be modified by a .
2. Int *const a
where const modifies a, and a represents a pointer address.
Therefore, it cannot be assigned to other address values ​​of a, but the value pointed to by a can be modified.
This is somewhat opposite to cont int *a. The example is Don't say anything

3. As for the meaning of int const *a and const int *a are the same, their two functions are equivalent

Supplement:
4. const int * const a
represents the value of the object pointed to by a and its address itself cannot be changed
5. const int *const a

Neither the object pointed to by a nor the value of the object can be changed.

A little bit about const:
1. The address of a const object can only be assigned to a pointer to a const object.
2. A pointer to a const object can be assigned the address of a non-const object.
3. A pointer to const is often used as a function. Formal parameters ensure that the actual object passed to the function will not be modified in the function.
4. The constant cannot be modified after it is defined, so it must be initialized. Uninitialized constant definitions will cause compilation errors (the above are all explaining the const problem, so there is no assignment, which must be assigned in the actual statement)

#include "stdio.h"
int a = 0;
int b = 1;
int c = 2;
int main(void)
{
	const int *pa = &a;    //值不能改变 
	int const *pb = &b;    //值不能改变 
	int * const pc = &c;   //地址不能改变 
	printf("*pa = %d\r\n*pb = %d\r\n*pc = %d\r\n",*pa,*pb,*pc);
	printf("pa = 0x%x\r\npb = 0x%x\r\npc = 0x%x\r\n",pa,pb,pc);
	pa = &b;   //地址改变,允许
//	*pa = 3;   //值改变,不允许 
	pb = &a;   //地址改变,允许
//	*pb = 3;   //值改变,不允许 
//	pc = &b;   //地址改变,不允许
	*pc = 3;   //值改变,允许 
	printf("*pa = %d\r\n*pb = %d\r\n*pc = %d\r\n",*pa,*pb,*pc);
	printf("pa = 0x%x\r\npb = 0x%x\r\npc = 0x%x\r\n",pa,pb,pc);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_40831436/article/details/112196217