Explore the const keyword

Table of contents

introduce

modified variable

modified function

modified pointer


Introduction: When talking about the const keyword in C language, it is often used to describe a constant, that is, a variable whose value is immutable during the execution of the program. In this blog, we will delve into the role and usage of const.


introduce

The const keyword in C language is often used to modify variables, which is intended to modify variables into constant attributes, thereby protecting the variable from being modified and thus avoiding the occurrence of some bugs and errors.


modified variable

 We can see that when we use const in front of a, the value of a can no longer be modified.

This is also the most common usage of const.


modified function

Mainly modify the parameters and return values ​​of functions

Modification parameters

​
void fun(const a) {
	//函数中不能通过指针来修改a
	a = '2';//err
	printf("%c", a);
}

​

a in the function cannot be modified 

 Modify return value

const int fun(int a,int b) {
    // 返回a和b中的最大值作为常量
	return a > b ? a : b;
}

The return value a or b cannot be modified


modified pointer

As shown in the figure, it is still the first example. We have locked the variable a here so that it cannot be changed, but we found the address of a through the pointer p and modified it. So in order to prevent this phenomenon, we introduced the use of const to modify pointers.

 1. Put const in front of *

int main()
{
	const int a = 10;
	const int* p = &a;
	*p = 20;//err
    p = 20;//ok
	printf("%d", a);
	return 0;
}

The const here modifies *p (the variable pointing to the address of a), thus preventing the variable a from being modified by modifying *p.

But it does not affect p pointing to other addresses

2. Put const after *

int main()
{
	const int a = 10;
    int* const p = &a;
	*p = 20;//ok
    p = 20;//err
	printf("%d", a);
	return 0;
}

The const here modifies p (pointer variable), and its function is to no longer allow the variable p to point to other addresses.


Summary: The above is all my understanding of the const keyword, thank you for watching! !

Guess you like

Origin blog.csdn.net/2301_77125473/article/details/132306750