One, macro definition #define and constant const
1.
const keyword
Const is a shorthand for constant , as long as a variable is preceded by a const modifier, it means that the data in the variable can be accessed and cannot be modified. In other words, const means read-only (ReadOnly).
Const modifies a variable, it must initialize the value of the variable, and if it is not initialized, it cannot be initialized later.
1.1
#include <iostream>using namespace Std;int main () { const double pi; Pi is used to denote the value of pi pi=3.14159265; cout<< "The approximate value of pi is" <<pi<<endl; return 0;}
Error, no initialization. Read-only.
1.2
#include <iostream>using namespace Std;int main () { const double pi=3.141592; The value of pi is denoted by pi cout<< "PI approximate value is" <<pi<<endl; return 0;}
1.3
const keyword App
- To prevent a variable from being changed, you can use const, which is initialized when you define the const variable, and there is no chance to change it.
- For pointers, you can specify that the pointer itself is const, or that the data that the pointer refers to is const, or both are specified as const;
- In a function declaration, a const can modify a formal parameter to indicate that he is an input parameter and that its value cannot be changed inside the function;
- For a member function of a class, it is sometimes necessary to specify that it is a const type, indicating that it is a constant function and cannot modify the member variables of the class;
- For a member function of a class, you must sometimes specify that its return value is a const type so that its return value is not a "left value"
2.
Differences between macro definitions #define and const constants
Different types and security checks
Macro definition is a character substitution, there is no difference between data types, and this substitution has no type security check, may produce marginal effect and other errors;
Const constants are declarations of constants, types differ, and type checking is required during the compilation phase
The compiler handles different
The macro definition is a "compile-time" concept, which is expanded during preprocessing, and the macro definition cannot be debugged, and the life cycle ends at compile time;
A const constant is a "run-time" concept that is used in a program run, similar to a read-only row of data
Different storage methods
A macro definition is a direct replacement that does not allocate memory, stored with the program's code snippet;
Const constants need to be allocated in memory, stored with the program's data segment
2.1
2.2
2.3
C + + Constants