Let’s talk about const and static qualifiers

const is a constant qualifier. When a variable modified by const is allocated memory, its value must be initialized at the same time. It cannot be modified later.
For example:
const int a;
When a is defined outside the function, that is, it is a global variable, then a is Automatically initialized to 0.
When a is defined in a function, that is, it is a local variable, then const int a = rvalue; //This is how to display initialization. Otherwise it won't compile.

void func_1() {
    
    
	const int d = 10;
	int* j = (int*)&d;
	*j = 1;
	cout << __func__ << ": " << " d = " << d << ", *j = " << *j << endl;//func_1:  d = 10, *j = 1
}

Code analysis:
const int d = 10;//This kind of defined constant variable will be optimized at compile time to where the variable d is used within the scope. , are replaced by the integer literal value 10, but the address of variable d will not be replaced.
int* j = (int*)&d;//Force the address type of the constant variable to a non-const type pointer. Pointer j points to constant variable d. This is a dangerous practice and not recommended. The optimization of the previous sentence of code is compiled to prevent forced situations.
*j = 1; //Modify the value of constant variable d.
The variable d in the output statement has been replaced by 10 during the compilation stage. This is why even if the value in d is modified to 1, the printed value is still 10.
Insert image description here

void func_2() {
    
    
	int b = 10;
	const int d = b;
	int* j = (int*)&d;
	*j = 1;
	cout << __func__ << ": " << " d = " << d << ", *j = " << *j << endl;//func_2:  d = 1, *j = 1
}

const int d = b;//In this case, the value of d can only be determined when func_2() is executed, so the variable d will not be used elsewhere in its scope at compile time. Make a substitution.
So in the end, the d printed in the output statement is modified.
Insert image description here
注意: const modifier, which generally modifies the formal parameters of functions and is used when defining global constants. Generally, variables are not used inside functions.
Although a variable inside a function is modified by the const modifier, it is still a local variable on the stack. After the function is executed, its memory is released.

void func_3() {
    
    
	int a = 6;
	static int c = 7;
	const int d = 10;
	printf("地址a: %p\n",&a);
	printf("地址c: %p\n",&c);
	printf("地址d: %p\n",&d);
}
int main()
{
    
    
	func_3();//第一次调用
	func_3();//第二次调用
}

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/adminstate/article/details/134922727