# Difference between define and const

Source: Internet
Author: User

# 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.