Recently began preparing for a lab study while documenting some of the programming trivia points encountered. Today when testing the SVD decomposition of matrices, we need to define the size of the rows and columns of the matrix, and I used to define these two variables with a macro definition, and when I run, I start thinking about what the difference between the macro definition and the constant is.
Refer to some other people's statements, I do a small summary here.
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
Macro definition is a "compile-time" concept, in the preprocessing phase, the macro definition can not be debugged, the end of life cycle and 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
define domains differently
void F1 () {#define N Const intN A; } void F2 () {cout<<n <<endl;//correct, N has already been defined and is not subject to defined domain limits cout<<n <<endl;//error, n definition field only in F1 function}
can be canceled after definition
Macro definitions can be #undef
invalidated by the previous macro definition
Const constants are permanently valid within the defined field after they are defined
void F1() {#define N Const intn = A;#undef n //After canceling the macro definition, even in the F1 function, N is not valid #Define N//cancellation can be redefined }
is it possible to do function parameters
A macro definition cannot be passed as a parameter to a function
Const constants can appear in the argument list of a function
The difference between a macro definition (#define) and a constant (const)