# DefineAndConstDifference
Although they feel "almost" in use, what are their differences in implementation?
See the following code:
# Define T 13/* use # A constant defined by define T */
Int main ()
{
Const int T = 13;/* a constant defined by const */
Int n = T;/* assign t to N */
Int M = T;/* assign t to M */
}
1.Difference:
The biggest difference between const and # define is that the former allocates space in the stack, while the latter only transfers the specific value directly to the target variable. Or, the const constant is a run-time concept, and its existence in the program can be called and passed. The # define constant is a compile-time concept. Its life cycle ends at the compilation period. In an actual program, it is only a constant, a parameter in a command, and does not actually exist.
Const constants exist in the Data Segment of the program.
# Define constants exist in the code segment of the program.
2Advantages and disadvantages:
The advantages and disadvantages of the two depend on the specific situation. I personally think that # define is a better choice for constant applications:
I. From the run-time perspective, he has good advantages in space and time.
Ii. From the perspective of compile-time, code similar to M = T * 10 will not be optimized by the compiler, and T * 10 operations need to be executed in run-time. The # define constants are merged.
However, if you need to modify the constant value rudely, use const because the latter does not actually exist in the program.