Const qualifier
1. Use const to give literal constants a name (identifier), which is called an identifier constant, because the declaration and usage of an identifier constant is much like a variable, so it is also called a constant variable
2. General form of definition:
(1) const data type constant name = constant value;
(2) Data type const constant name = constant value;
3. For example: const float pi=3.14159f;
4. Precautions:
(1) Constant variables must be initialized at the time of definition;
(2) After initialization of the constant variable, it is not allowed to be assigned again;
code example:
Main.cpp#include <iostream>using namespace std;//introduces namespace int main (void) {//const int a;//1.error, constants must initialize const int a = 100;//A = 200;//2.error, constants cannot be re-assigned int b = 22;const int * P;//const on the left, indicating *p as constant, via *p cannot change what the pointer points to P = &b;//*p = 20 0;//2.error, constants cannot be re-assigned//int * Const P2;//1.ERROR,P2 is constant, constants must initialize int * Const P2 = &b;//const on * Right, P2 is constant//int c =100;// P2 = &c;//2.error, constants cannot be re-assigned *P2 = 200;cout<<b<<endl;cout<<*p<<endl;return 0;}
Error usage compilation error message:
1. constintA;
error C2734: "A": if it is not external, you must initialize the constant object
2. constinta = 100; a = 200;
error C3892: "A": cannot assign a value to a constant
Learn C + + from C to C + + (const qualifier) with me