Usage and difference between typedef and # define

Source: Internet
Author: User

Usage and difference between typedef and # define

I. Usage of typedef

In C/C ++, typedef is often used to define an alias for an identifier and a keyword. It is part of the language compilation process, but it does not actually allocate memory space, such:

Typedef int;
Typedef int array [10];
Typedef (int *) pint;

Typedef can be enhancedProgramBut it also has some disadvantages such as "non-intuitive.

 

Ii. # define usage

# Define is a macro Definition Statement, which is usually used to define constants (including non-parametric and parametric), and macros used to implement "superficial goodness, long strings behind", which are not compiled

This process is completed before (preprocessing), but it is difficult to find potential errors and other problems.CodeMaintenance problem. Its instance is like:

# Define int
# Define true 1
# Define add (A, B) (a) + (B ));
# Define loop_10 for (INT I = 0; I <10; I ++)

In clause 1 of Scott Meyer's Objective C ++, we have analyzed the disadvantages of # define statements and good alternatives. For more information, see.

 

Iii. Differences between typedef and # define

From the above concepts, we can also understand that typedef is just a new name (only an alias) for the identifier to increase readability, and # define is originally used to define constants in C.

The emergence of C ++, const, Enum, and inline gradually makes it an alias tool. Sometimes it is easy to figure out which one should be used with typedef, for example, # define

A statement like an int can be completed using typedef. Which one is better? I advocate the use of typedef, because in many early C compilers, this statement is invalid, but today's

The compiler has been expanded. To be as compatible as possible, we generally follow # define to define "readable" constants and macro statement tasks, while typedef is often used to define keywords and redundancy.

Long TYPE alias.

Macro definition is just a simple string replacement (in-situ extension), while typedef is not in-situ extension, and its new name has a certain encapsulation, so that the identifier of the new name is easier to define and change.

Capacity. See the third line of the first code:

Typedef (int *) pint;
And the following line:
# Define pint2 int *

Same effect? Actually different! In practice, see the difference: pint a, B; has the same effect as int * A; int * B; indicates that two integer pointer variables are defined. Pint2 a, B; has the same effect as int * a, B;

Defines an integer pointer variable A and an integer variable B.

Four uses and two traps of typedef

Purpose 1:
Define a type of Alias, not just a simple macro replacement. It can be used as multiple objects that declare the pointer type at the same time. For example:
Char * pA, PB; // most of them do not conform to our intention. It only declares a pointer to a character variable,
// And a character variable;
The following are feasible:
Typedef char * pchar; // generally, uppercase is used.
Pchar Pa, PB; // feasible. Two pointers pointing to character variables are declared at the same time.
Although:
Char * pA, * pb;
It is also feasible, but it is not intuitive in the form of typedef, especially where a large number of pointers are required, the typedef method is more convenient.

Purpose 2:
It is used in the old C code (not checked for many old ones) to help struct. In the previous Code, when declaring a new struct object, you must carry the struct, that is, the form is: struct structure name object name, such:
Struct tagpoint1
{
Int X;
Int y;
};
Struct tagpoint1 P1;

In C ++, you can directly write: Structure name Object Name, namely:
Tagpoint1 P1;

It is estimated that it is too troublesome for someone to write another struct, so they invented:
Typedef struct tagpoint
{
Int X;
Int y;
} Point;

Point P1; // in this way, a struct is written less than the original method, which is easier to use, especially when it is used in a large amount.

Maybe, in C ++, typedef is not very useful, but understanding it is helpful for mastering the old code, after all, we may encounter code that was left behind in earlier years in the project.

Purpose 3:
Use typedef to define platform-independent types.
For example, define a floating point type called real. On the target platform 1, make it the highest precision type:
Typedef long double real;
On Platform 2 that does not support long double, change:
Typedef double real;
On Platform 3 that is not supported by double, change:
Typedef float real;
That is to say, when using a cross-platform system, you only need to change the typedef itself, without any modifications to other source codes.
This technique is widely used in the standard library, such as size_t.
In addition, because typedef defines a new type of Alias, it is not a simple string replacement, so it is more robust than a macro (although it can do the above when a macro is used ).

Purpose 4:
Define a new simple alias for complex statements. The method is: gradually replace a part of the complex declaration with an alias in the original declaration. In this loop, leave the part with the variable name to the final replacement, and the most simplified version of the original declaration is obtained. Example:

1. Original Declaration: int * (* A [5]) (INT, char *);
The variable name is A. replace a with a new alias pfun:
Typedef int * (* pfun) (INT, char *);
The most simplified version of the original statement:
Pfun A [5];

2. Original Declaration: void (* B [10]) (void (*)());
The variable name is B. Replace pfunparam with alias 1 in the brackets on the right:
Typedef void (* pfunparam )();
Replace B with the variable on the left, and pfunx with alias 2:
Typedef void (* pfunx) (pfunparam );
The most simplified version of the original statement:
Pfunx B [10];

3. original statement: Doube (*) (* E) [9];
The variable name is E. Replace the left part with pfuny as Alias 1:
Typedef double (* pfuny )();
Replace the variable E on the right, and pfunparamy is alias 2.
Typedef pfuny (* pfunparamy) [9];
The most simplified version of the original statement:
Pfunparamy E;

Understand the "right-left rule" available for complex statements: Starting from the variable name, you must first go to the right and then to the left. When you encounter a parentheses, you can adjust the reading direction. After analyzing the parentheses, you can jump out of the brackets, it is still in the order of the first right and then the left, until the entire declaration analysis is complete. Example:
INT (* func) (int * P );
First, find the variable name func, and there is a pair of parentheses on the outside, and there is a * sign on the left, which indicates that func is a pointer. Then jump out of the parentheses and look at the right first, this indicates that (* func) is a function, so func is a pointer to this type of function, that is, a function pointer. This type of function has an int * type parameter, and the return value type is int.
INT (* func [5]) (int *);
The right side of func is a [] Operator, indicating that func is an array with five elements; there is a * on the left of func, indicating that the func element is a pointer (note that * is not a modifier of func, instead, modify func [5] Because the [] operator has a higher priority than *, and func is first combined ). Jump out of the brackets and look at the right side. The parentheses indicate that the element of the func array is a pointer of the function type. It points to an int * type parameter and the return value type is int.

You can also remember two modes:
Type (*) (...) function pointer
Type (*) [] array pointer
---------------------------------

Trap 1:
Remember, typedef defines a new type of alias. Unlike macros, typedef is not a simple string replacement. For example:
First, define:
Typedef char * pstr;
Then:
Int mystrcmp (const pstr, const pstr );

Is const pstr actually equivalent to const char? No, it is actually equivalent to char * Const.
The reason is that const gives the entire pointer itself constant, that is, the constant pointer char * const is formed.
Simply put, remember that when const and typedef appear together, typedef won't simply replace strings.

Trap 2:
Typedef syntax is a storage class keyword (such as auto, extern, mutable, static, register, etc.), although it does not really affect the storage features of objects, such:
Typedef static int int2; // not feasible
Compilation will fail, and the system will prompt "more than one storage class is specified ".

Address: http://www.cnblogs.com/kerwinshaw/archive/2009/02/02/1382428.html

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.