C + + can define constants with const, or you can define constants in # #, but the former is a bit more than the latter:
(1) const constants have data types, and macro constants do not have data types. The compiler can perform type safety checks on const, with only character substitutions, no type safety checks, and unexpected errors in character substitution! (such as type mismatch issues)
(2) Compiler processing method is different. Define macros are expanded during the preprocessing phase, and const constants are used during the compile run phase.
(3) different storage methods. Define macro is only expanded, there are many places to use, it expands how many times, does not allocate memory. Const constants are allocated in memory (either in the heap or in the stack).
There are a few things to keep in mind when using the Const modifier:
(1) When defining constants using the const modifier, it must be initialized.
(2) Once a constant is defined, it can no longer be changed anywhere in the program.
(3) const-defined constants can have their own data types, so that the C + + compiler can do more rigorous type checking. If you define an integer constant with const, int can be omitted.
(4) The function parameter can be described with a const, to ensure that the argument is not changed inside the function, most C + + compilers can have a const parameter of the function for better code optimization.
(5) The return value of the function is const only when the function is returned as a reference. A function return value reference constant indicates that a function call expression cannot be used as an lvalue.
(6) In a class, you can add a const to the member function definition of a class to indicate that the function is a "read-only function", that the function cannot change the state of the class object, and that the value of the member variable of the object cannot be changed. The const member function also cannot invoke other non-const functions in a function.
There are three cases when const is used with pointers:
(1) A pointer to a constant, such as a const char *pc= "ABCD"; it declares a pointer to a constant variable pc, which does not allow changing the constant pointed to by the pointer, but since the PC is a normal pointer variable pointing to a constant, you can change the value of the PC.
(2) constant pointer, such as char *const PC = "ABCD"; It declares a pointer variable called a PC, which is a constant pointer to the character data and initializes the constant pointer with the address of "ABCD". The pointer cannot be moved, but the data it refers to can be changed.
(3) Constant pointers to constants, such as const char * const PC = "ABCD", declares a pointer variable called a PC, which is a constant pointer to a character constant, initializes the pointer with an "ABCD" address, the entire pointer itself cannot be changed, and the value it points to cannot be changed.
Const modifiers that are easy to ignore in C + +