After years of learning C, have you mastered the use of const? Are you confused about the use of const in your programming practice? Today, we will discuss the summary together, hoping to solve our doubts and provide reference.
The C const keyword is the abbreviation for constant. Some people immediately think of constant when they see const. In fact, const is quite powerful in C. It can modify variables, arrays, Pointers, function arguments, and so on. This article will make a detailed summary for the above several modification functions.
1. Modify variables:
C uses const to modify variables. The function is to declare variables as read-only and protect their values from modification. Examples are as follows:
const int i = 5;
The above example shows that variable I is read-only and cannot be changed; If you want to reassign I, say I = 10; Is wrong.
It is important to note that when a variable is defined, it must be initialized. The definition can also be written as int const I =5, which is also true.
In addition, const modifiers also save space. Usually, the compiler does not allocate space to ordinary const read-only variables. Instead, it stores them in a symbol table.
2. Decorate arrays
Const can also modify arrays in C, as in the following example:
const int array[5] = {1.2.3.4.5};
array[0] = array[0] +1; / / error
Copy the code
Array elements, like variables, have read-only properties that cannot be changed; Once changed, such as the program will report an error.
3. Decorate Pointers
Const pointer (C); const pointer (C); const pointer (C) The other is to make the pointer immutable. Examples are as follows:
int i = 5;
int j = 6;
int k = 7;
int h = 8;
const int * p1 = &i; / / definition 1
int * const p2 =&j; / / definition 2
int const * const p3 =&h; / / define 3
Copy the code
Two Pointers p1, P2, and p3 are defined above.
Const p1=20; const p1=20; const p1=20; However, the value of P1 can be changed, and there is no problem in reassigning p1, such as P1 =&k.
In definition 2, const is limited to p2. If p2=&k, an error will be reported. But * p2, that is, the value of the space it points to can be changed, such as * p2=80 is no problem, the program runs normally.
In redefinition 3, const limits both the pointer and the value to which the pointer points.
4. Modify function parameters
The const keyword decorates a function parameter, qualifying it to prevent it from being modified inside the function. The qualified function parameters can be ordinary variables or pointer variables. Examples are as follows:
void fun1(const int i)
{other statements... i++;// The value of I was changedOther statements}void fun2(const int *p)
{other statements... (*p)++;// The value of p pointing to space is changedOther statements}Copy the code