C ++ const related study notes Lesson

Study Notes content from: Ditai Software College Tangzuo Lin teacher's video, I appreciate your guidance

C language const:

1.const modified variable is read-only, or essentially variable
2.const modified local variables allocated space on the stack, it is possible to modify the value of the space pointer const modify the value of the local variable
3.const modified globally in the words of the variables allocate space program read-only memory area, change the value of the crash
4.const only useful at compile time, useless at runtime

PS: C language constants defined in the true sense, can only be defined by the enum enum, const not

In C ++ const:

1. When declared const met (not const reference) was placed in a constant (symbol table is a data structure within the compiler) in a symbol table
2. If it is found during compilation constants used to directly replace the value of the symbol table
3. If it is found following the compilation process corresponding to the case where the storage space assigned constants for compatibility :( C language)
(1) the global constant const, and the use of constant const extern
(2) using constant const & operator to

Note: C ++ compiler constants as const although it may allocate space, but does not use the value of its storage space

The sample program:

#include <stdio.h>

int main()
{
	const int c = 0;
	int* p = (int*)&c;

	*p = 5;

	printf("c = %d\n",c);//打印0,使用的是符号表里的值

	printf("*p = %d\n",*p);//打印5,使用的是c对应的内存空间的值

	return 0;
}
Published 15 original articles · won praise 0 · Views 109

Guess you like

Origin blog.csdn.net/u012321968/article/details/104449807