What is the difference between typedef and DEF?

Source: Internet
Author: User

1) #define是预处理指令, will not participate in the compilation process, only in the compilation of pre-processing simple replacement, do not check for correctness, whether the meaning is correct or not, only when compiling the source program has been expanded to find possible errors and error. For example:
#define PI 3.1415926
In the program: Area=pi*r*r will be replaced with 3.1415926*r*r
If you write the number 9 in the # define statement as the letter G preprocessing is also brought in.

2) A typedef is processed at compile time. It gives an alias to an already existing type within its scope, but you cannot use the typedef specifier inside a function definition.

3) typedef int * INT_PTR; With # define INT_PTR int *
The function is to use INT_PTR to represent the int *, but the two are different, as mentioned earlier, a simple substitution #define在预处理, whereas a typedef is not a simple substitution, but rather a type declared as a method of defining a variable. That is

#define int_ptr int *//相当于int * a, b; 只是简单的宏替换int//a, b 都为指向int的指针,typedef为int* 引入了一个新的助记符

This also explains why the following ideas are set up

typedef int * PINT;
#define PINT int *

So:
Const pint p;//p cannot be changed, but P points can be changed
The const PINT p;//p can be changed, but the content that P points to cannot be changed.

Pint is a pointer-type const pint p is a pointer to the lock p cannot be changed
The const PINT p is a const int * p Lock that is the object referred to by the pointer p.

4) Perhaps you have noticed that # define is not a statement do not add a semicolon at the end of the line, or a semicolon is replaced.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

What is the difference between typedef and DEF?

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.