C & C ++, Typedef with #define

zhaozj2021-02-16  83

First, Typedef usage

____ In the C / C language, Typedef is often used to define an identifier and keyword alias. It is part of the language compilation process, but it does not actually allocate memory space, instance image:

Typedef int int; type [10]; typedef (int *) Pint;

____typedef enhances the readability of the program, and the flexibility of the identifier, but it also has the disadvantages such as "non-intuitive".

Second, # define usage

____ # define is a macro definition statement, usually uses it to define constants (including non-argument and belt parameters), and the macro used to achieve "surface seems to be good, behind", it is not in the compilation process But before this (pretreatment process) has been completed, it is difficult to discover potential errors and other code maintenance issues, its instance image:

#define int int int INT # Define True 1 # Define Add (a, b) ((a) (b)); # define loop_10 for (int i = 0; i <10; i )

____ There is a analysis of the drawback of the #define statement in the clause 1 of Scott Meyer's Effective C , as well as a good alternative, you can see it.

Third, the difference between typedef and #define

____ From the above concept, it can be basically clear. TypedEf is just a new name (only a individual name) for increasing readability, while #define is originally in C to define constants, C , The emergence of const, enum, inline makes it gradually become a tool for alias. Sometimes it is easy to make it unclear which good, such as #define int int int int int int int int int int int int int int in, can be done with TypeDef, which is good? I advocate use typedef because this statement is illegal in many of many C compilers, but today's compiler has done it again. To be as compatible as much as possible, you generally follow #define definition "readable" constants and some macro statements, and TypeDef is often used to define keywords and lengthy alias.

____ macro definition is just a simple string restriction (original extension), and Typedef is not originally extended. Its new name has certain encapsulation, so that the newly named identifier has a function of more vulnerable variables. Please see the third line of the first big code above:

Typedef (int *) Pint; and below: #DEfine Pint2 Int *

____ Effect same? Real is different! See the difference in practice: Pint A, B; effect is the INT * a; int * b; indicates two integer pointer variables. Pint2 a, b; the effect is true with INT * a, b; indicates a constitutive pointer variable A and integer variable B.

____ Note: There is still a row of row; the difference!

转载请注明原文地址:https://www.9cbs.com/read-13960.html

New Post(0)