The problem of const and define on constant definition
In C + +, we encourage the use of const to define constants rather than macro define. There are many reasons.
One. Const is more elegant than define, and more in line with symbolic constants.
Two. Define in complex code, people who do not understand the substance of define will have problems. Define is the replacement of the code literal, and the preprocessing phase restores the replaced content. A typedef is a type (or compound type) in which a wrapper already exists, defining a new atomic type.
#include <iostream> #define days 365 int money = 100 ; int Main (void using namespace STD; int total = Days*money; cout <<total<<ENDL; System ( pause " ); return 0 ;}
After preprocessing
#include <iostream>Const intMoney = -; intMainvoid){ using namespacestd; intTotal =365*money;//the preprocessor replaces days with 356cout<<total<<Endl; System ("Pause"); return 0;}
Constants defined by const can be said to be "immutable variables" because it does use a variable to hold a value that does not change, and the constant defined by define is essentially a literal constant, and of course it does not change.
Who exactly modifies the const, which is the same?
I conclude that if the const is placed first, the const will cross over an atomic type and decorate the back. How to understand this sentence through the Code demo:
#include <iostream>intMainvoid){ using namespacestd; intA =1; Const int*p = &a;//int is an atomic type, the real effect is: int const*p = &a; //that is: when you manipulate a with pointer P, a is a constant and is read-only and not writable. System ("Pause"); return 0;}
#include <iostream>typedefint*Pint;intMainvoid){ using namespacestd; intA =1; ConstPint p = &a;//Pint is an atomic type, the real effect is: Pint Const P = &a; //that is: P is a constant, read-only and not writable. //p = NULL Error//*p = OKSystem ("Pause"); return 0;}
The dispute between the "C + +" typedef and the const