Define and typedef differences

Source: Internet
Author: User

C language Define and TypeDef, both have similarities, but also different points.


Here is a similarity between the two:

The C language allows typedef to define a new name for various data types, and the TypeDef declaration is basically the same as the normal declaration, except that the typedef appears in front of the declaration.

For example: typedef char *PTR;  

This declaration uses the identifier PTR as a new name for the pointer type pointing to the character pointer, which can be used in the following declaration, as with any predefined name.

For example: ptr A; (Declaring A is a pointer to a character)

For macro define:

Example: #define PTR char *

PTR A;

This PTR, defined by define, is replaced with a char * type, which makes a a pointer to a character type, which is the same as the effect of the preceding typedef.


Here are the specific differences:

1) #define是预处理指令, in the compilation of pre-processing only simple substitution, not for correctness check, whether the meaning is correct only replace, only the execution of the program will find errors and error.

Example: #define PI 3.1415926
In the program: Area=pi*r*r is replaced with 3.1415926*r*r, if the number 9 in the # define statement is written as the letter G preprocessing is also brought in.

2) A typedef is processed at compile time, giving an alias to an already existing type within its own scope.


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 previously said, #define在预处理时进行简单的替换, and typedef is not a simple substitution, but rather a way of declaring a type as a method of defining a variable.

4) #define不是语句, do not add semicolons at the end of the line, or they will be replaced with a semicolon.

This article from "Unintentional persistent" blog, reproduced please contact the author!

Define and typedef differences

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.