What is a const?
What is a # define?
What's the use of them?
What difference do they have?
What should I do with it?
Summarize
1. What is a const?
Const is a keyword (modifier) in C/s + +, which is typically used to define a constant that, since it is called a constant, cannot modify its value later.
Const definition Constants
2. What is a # define?
and define, a macro definition, is a precompiled instruction that the compiler will simply replace in the compilation phase where all the macros are used. As shown in the following:
Substitution of macro Definitions
3. What's the use of them?
Both const and define can define a constant, all of which can be modified once, and all the places where the constant is used are changed synchronously, without changing the code.
Make code easier to maintain
Increase the efficiency of your code
4. What is the difference between them?
Same point
Different points
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
Const and define Differences
The compiler typically does not allocate storage space for ordinary const constants, but instead saves them in the symbol table, which makes it a constant during compilation, without the storage and read memory operations, making it more efficient than macro definitions
Now that the macro definition can do what the const can do, is there any need for the macro to exist?
Existence is reasonable, since the macro definition has not been eliminated, there must be a reason for its existence.
A macro can do what a const can't do.
Macros can define functions
OC Singleton mode with macro
Macros can also generate strings based on the parameters passed in, as follows
Macros define advanced Features
Kstringcat (x, y)//concatenation of strings according to incoming X and Y
Ktostring (x)//Generate a string based on the x passed in
5. What should I do with it?
The const has a principle, and that is what is on his right and what is immutable, as follows
Const immutable Principle
Using const to modify the formal parameters of the function can improve the security of the code, while reducing the communication costs between programmers
Only X and y can be used inside the function, and cannot be changed
Macros are used for conditional compilation, and if you need to execute different blocks of code for different situations, you can use the macro's conditional compilation to make judgments
Summarize
In Objective-c, const constants can be seen everywhere, so you should be bold to use const, which will bring you great benefits. At the same time, once a data is defined and is never needed or modified, use const!
15 minutes to get a sense of const and #define