Static and Const are the keywords in C language, they can modify variables, functions, and so on.
1.const
Const and variable
int x = 5; Variable
const int x = 5;//in C + +, X is constant, and in the C language, X is an immutable variable
Const and Pointer types
int a = ten;
int b =;
int *PA = &a;
int **ppa = &pa;
*ppa = &b;
**ppa = 30;
We use graphs to denote various pointing relationships.
Note: The address given in the figure is hypothetical, not the real address. ~~
(i) const and first-level pointers
eg
int a=;
int const *PA = &a;
*PA = 30;
The 2nd sentence is that the content that the PA points to is immutable, and the 3rd sentence changes the content that the PA points to, so the above code is incorrect.
int *const pa = &a;
PA = &b;
The const modifier PA, so, PA content can not be changed, that is, inside only a address of a, statement 3 changed the content of PA, so the above code is wrong.
(ii) const and level two pointers
eg
int *PA = &a;
int **const PPA = &pa;
*ppa = &b;
The PPA cannot be changed and only the PA address can be stored inside. Statement 3,ppa The address of B, and statement 4 is to change the contents of the address of B that the PPA points to 30. The PPA has not changed, so the above procedure is correct.
eg
int *const * PPA = &pa;
*ppa = &b;
The point of the PPA is that the *ppa cannot be changed, and the 2nd statement changes the point of the PPA, error.
eg
int const * PPA = &pa;
**PA = 30;
The point of the PPA is not to be changed, error.
Const and Reference
int x = 3;
const int &y = x;
y = 5;//Error
2.static
(1) ststic modifier function: This function can only be visible in the current. c file, so that a function of the same name is defined in a different. c file without causing a conflict, as long as one of the functions is modified with static;
(2) Static modified local variable: Static variable defined in a function, only this function can read it, its value in the execution of the program has been maintained;
(3) Static modifier global variable: ststic variable defined in a file, only this file can read it.
Below we look at an example:
#define _crt_secure_no_warnings 1
#include <stdio.h>
void fun1 ()
{
int i = 0;
for (i = 0;i < 10;i++)
{
static int m = 0;
m++;
printf ("%d", m);
}
printf ("\ n");
}
void Fun2 ()
{
int i = 0;
for (i = 0;i < 10;i++)
{
int m = 0;
m++;
printf ("%d", m);
}
}
int main ()
{
fun1 ();
Fun2 ();
System ("pause");
return 0;
}
The result of the program running is this. Two functions appear to be similar, that is, fun2 m is int, and FUN1 m is defined as static. When static modifies a local variable, his value is persisted throughout the execution of the program.