Typedef vs # define (const) Usage

Source: Internet
Author: User

I think the materials I have prepared are quite important.

1) # define is a pre-processing command. It is a simple replacement during compilation and pre-processing, and does not check the correctness. It does not mean that it is correct or not, possible errors are detected and reported only when the expanded source program is compiled. For example:

# Define PI 3.1415926

In the program: Area = pI * r will be replaced with 3.1415926 * r * R

If you write the number 9 in the # define statement as a letter g, the preprocessing will also be carried in.

2) typedef is processed during compilation. It gives an existing type an alias in its own scope, but you cannot use the typedef specifier inside a function definition.

3) typedef int * int_ptr; and # define int_ptr int *

Int_ptr is used to represent int *, but the two are different. As mentioned above, # define is replaced simply during preprocessing, while typedef is not a simple replacement, instead, declare a type as if the variable is defined. That is to say;

// Refer to (xzgyb (Lao Damo ))

# Define int_ptr int *

Int_ptr a, B; // equivalent to int * a, B; just a simple macro replacement

Typedef int * int_ptr;

Int_ptr a, B; // A and B all point to the int pointer. If typedef is int *, a new mnemonic is introduced.

This also explains why the following points are true:

// Qunkangli (the maintenance cost is directly proportional to the programmer's creativity)

Typedef int * pint;

# Define pint int *

So:

Const pint P; // P cannot be changed, but the content pointed to by P can be changed

Const pint P; // P can be changed, but the content pointed to by P cannot be changed.

Pint is a pointer type. Const pint P is used to lock the pointer. P cannot be changed.

Const pint P is the object indicated by pointer p.

3) You may have noticed that # define is not a statement. Do not add points at the end of the line. Otherwise, a semicolon is replaced.

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.