Const can limit the value of a variable not allowed to be changed, using the const to some extent can improve the security and reliability of the program
const int a = 10;
The value of variable a cannot be modified, it is always the initial 10
int const A = 10; is equivalent to the above notation
void sum (const int A, const int b)
The above function prevents others from tampering with the value of the parameter
As you can see, const can be used to define a constant. function with enum, #define类似
The following example shows that P is a constant and can no longer be assigned p, so p can not point to another variable
int a = 10;
int * Const P = &a;
The following example indicates that *p is a constant and cannot be modified by *p to modify the value of variable a
int a = 10;
const int *P = &a;
The following example prevents the parameter a pointer of the test function from modifying the value of the outside age variable
void Test (const int * a);
int age = 10;
Test (&age);
The following example shows that both *p and P are constants
int a = 10;
const INT * Const P = &a;
Const and # define
Both const and # define can be used to define constants, which can result in a change to all of them.
In fact, it is more recommended to use Const or enum to define constants
The initial purpose of the const rollout is to replace the precompiled directive, eliminate its drawbacks, and inherit its advantages
Const can save space and avoid unnecessary memory allocations. Example:
#define PI1 3.14159//Macro Constants
Const double PI2 = 3.14159; Pi is not placed in RAM at this time
Double A = PI2; Allocate memory for PI at this time, no longer assigned!
Double b = PI1; Macro substitution during compilation, allocating memory
Double C = PI2; No memory Allocations
Double d = PI1; Another macro replacement, another memory allocation!
Const definition constants from a compilation point of view, just give the corresponding memory address, instead of the immediate number as given in # define, so the const definition of the constant in the program run only one copy, and # define the constants in memory have several copies
#define的副作用
#define有时候会产生一些不好的副作用, such as the following example:
MAX macro returns the maximum value from two values
#define MAX (x, y) ((x) > (y)? (x): (y))
int a = 10;
int B = 6;
int c = MAX (++a, b);
cout << "c =" << C << ", a =" << a << Endl;
This time the output is:c =, a =
If the initial value of variable B is changed to 15, that is int b = 15;
The output of this time is:C = all, a = one
#define的特殊用途
#define还是有它无可取代的地方, like
Pass in a parameter, and then generate a string
#define TO_STR (x) #x
cout << to_str (ABCD) << Endl;
Concatenate multiple parameters to synthesize a complete identifier
#define CONCAT (x, y) x# #y
int myage = 20;
cout << CONCAT (My, age) << Endl;
Xcode learns C + + (third, const)