Usage Summary of typedef and its difference with define

Source: Internet
Author: User
Tags define definition

Difference between typedef and define


The following code is used to describe

Typedef char * typedef_char;
# Define define_char char * // No semicolon here

Void main (INT argc, char * argv [])
Char s [] = "ASDF ";
Const typedef_char P = s; // char * const
* P = 'B'; // The P pointer is a constant pointer. It cannot point to anything else, but the content to which it points can be changed.

Cout <"P =" <S <Endl; // bsdf

Const define_char q = s; // const char *
// * Q = 'X'; // The Pointer Points to a constant. Therefore, an error occurs when modifying the pointer.
Cout <"q =" <q <Endl; // ASDF

Note: typedef is interpreted by the compiler, while define is a simple replacement, meaning that typedef char *
Typedef_char; The typedef_char in it is interpreted by the compiler as a char *. in use, const
Typedef_char P is a const type char * pointer, and then translated as char * Const.

Typedef usage

Role of typedef declaration:

Typedef can hide clumsy Syntax structures and platform-related data types to enhance portability and future maintainability.

(1) helps to create platform-independent types

(2) hiding complex and incomprehensible syntaxes



1. Create a new name for the original type and define a type name that is easy to remember
Typedef is used most often to create a type name that is easy to remember and use it to archive the programmer's intent. Type appears in the declared variable name, which is on the right of the ''typedef ''keyword. For example:
Typedef int size;
This statement defines an int synonym with the name size. Note that typedef does not create a new type. It only adds a synonym for an existing type. You can use size in any context that requires an int:
Void measure (size * psz );
Size array [4];
Size Len = file. getlength ();
STD: vector;
Typedef can also conceal conforming types, such as pointers and arrays. For example, you do not need to repeatedly define an array with 81 characters as follows:
Char line [81];
Char text [81];
Define a typedef. Whenever an array of the same type and size is used, you can do this:
Typedef char line [81];
Line Text, secondline;
Getline (text );

2. Create platform-independent data types to hide clumsy and incomprehensible syntaxes
Hide the pointer syntax as follows:
Typedef char * pstr;
Int mystrcmp (pstr, pstr );
This will take us to the first typedef trap. The standard function strcmp () has two 'const char * 'parameters. Therefore, it may mislead people to declare mystrcmp () as follows ():
Int mystrcmp (const pstr, const pstr );
This is incorrect. In order, 'const pstr' is interpreted as 'Char * const' (a constant pointer to Char ), instead of 'const char * '(pointer to constant char ). This problem can be easily solved:
Typedef const char * cpstr;
Int mystrcmp (cpstr, cpstr); // It is correct now
Remember: Whenever typedef is declared for the pointer, a const must be added to the final typedef name so that the pointer itself is a constant rather than an object.
Simplified code
The typedef behavior discussed above is a bit like the # define macro, which replaces the synonym with its actual type. The difference is that typedef is interpreted during compilation, so let the compiler handle text replacement beyond the pre-processor capability. For example:
Typedef int (* PF) (const char *, const char *);
This statement introduces the PF type as the synonym of the function pointer. This function has two parameters of the const char * type and a return value of the int type. If you want to use the following form of function declaration, the above typedef is indispensable:
PF register (PF );
The Register () parameter is a PF type callback function that returns the address of a function with the same signature as the previously registered name. Take a deep breath. The following shows how to implement the declaration without typedef:
INT (* Register (INT (* PF) (const char *, const char *)))
(Const char *, const char *);
Few programmers understand what it means, not to mention the risk of errors caused by such obscure code. Obviously, using typedef is not a kind of privilege, but a necessity. Skeptical people may ask: "OK, will someone write such code? ", Quickly browse the header file that reveals the signal () function, a function with the same interface.
Typedef and Storage Class specifier)
This is not surprising. typedef is like auto, extern, mutable, static. Like register, it is a storage keyword. This means that typedef will really affect the Storage Feature of objects. It only means that in the statement structure, the typedef declaration looks like a variable declaration of static, extern, and other types. The following is a second trap:
Typedef register int fast_counter; // Error
Compilation and translation fail. The problem is that you cannot have multiple storage-class keywords in the Declaration. Because the symbol typedef occupies the storage class keyword, register (or any other storage class keyword) cannot be used in the typedef declaration ).
Promote cross-platform development
Another important purpose of typedef is to define machine-independent types. For example, you can define a floating point type called real. On the target machine, it can obtain the highest precision:
Typedef long double real;
On a machine that does not support long double, the typedef looks like the following:
Typedef double real;
In addition, on a machine that does not support double, the typedef looks like this :,
Typedef float real;
You do not need to make any changes to the source code, you can compile this real-type application on each platform. The only change is typedef itself. In most cases, even this tiny change can be automatically implemented through fantastic Conditional compilation. Isn't it? The standard library uses typedef to create such platform-independent types: size_t, ptrdiff, and fpos_t. In addition, typedef such as STD: string and STD: ofstream also hides long, incomprehensible template-specific syntax, such as basic_string, Allocator>
And basic_ofstream>.
Author Profile
Danny Kalev is a certified system analyst who specializes in C and formal language theories. He was a member of the C Standards Committee from 1997 to 2000. Recently, he completed his master's thesis on general linguistics with outstanding achievements. In his spare time, he enjoys listening to classical music, reading Victorian literature, and studying natural languages such as Hittite, Basque, and Irish Gaelic. Other interests include archaeology and geography. Danny often goes to some C forums and regularly writes articles for different C websites and magazines. He also teaches programming languages and application languages at educational institutions.
Source 2: (; id = 4455)
Usage of typedef in C Language
1. Basic explanation
Typedef is a key word in C language. It defines a new name for a data type. The data types here include internal data types (INT, Char, etc.) and Custom Data Types (struct, etc ).
In programming, typedef is generally used for two purposes. One is to give a variable a new name that is easy to remember and clear, and the other is to simplify some complicated type declarations.
As for the subtlety of typedef, let's take a look at the specifics of several problems.
2. typedef & Structure Problems
When the following code defines a structure, the compiler reports an error. Why? Does the C language not allow the structure to contain pointers to itself? First, let's look at the following description:
Typedef struct tagnode
Char * pitem;
Pnode pnext;
} * Pnode;
Answer and analysis:
1. The simplest use of typedef
Typedef long byte_4;
Give a new name for the known data type long, called byte_4.
2. Use typedef in combination with the structure
Typedef struct tagmystruct
Int inum;
Long llength;
} Mystruct;
This statement actually completes two operations:
1) define a new structure type
Struct tagmystruct
Int inum;
Long llength;
Analysis: tagmystruct is called "tag", that is, "tag". It is actually a temporary name. The struct keyword and tagmystruct constitute this structure type, whether or not there is typedef, this structure exists.
We can use struct tagmystruct varname to define variables, but note that it is incorrect to use tagmystruct varname to define variables, Because struct and tagmystruct can be combined to represent a structure type.
2) typedef is named mystruct for the new structure.
Typedef struct tagmystruct mystruct;
Therefore, mystruct is actually equivalent to struct tagmystruct. We can use mystruct varname to define variables.
Answer and Analysis
C language certainly allows a pointer to its own in the structure. We can see countless such examples in the implementation of data structures such as the establishment of a linked list. The fundamental problem of the above Code lies in the application of typedef.
According to the above description, we can know that the pnext domain declaration is encountered during the creation of the new structure. The type is pnode. You must know that pnode represents the new name of the type, when the type itself is not created, the new name of the type does not exist. That is to say, the compiler does not know pnode at this time.
There are many ways to solve this problem:
1 ),
Typedef struct tagnode
Char * pitem;
Struct tagnode * pnext;
} * Pnode;
2 ),
Typedef struct tagnode * pnode;
Struct tagnode
Char * pitem;
Pnode pnext;
Note: In this example, you use typedef to give a new name for a type that is not fully declared. C language compiler supports this approach.
3) standard practices:
Struct tagnode
Char * pitem;
Struct tagnode * pnext;
Typedef struct tagnode * pnode;
3. typedef & # define
There are two methods to define the pstr data type. What are the differences between the two? Which one is better?
Typedef char * pstr;
# Define pstr char *;
Answer and analysis:
Generally, typedef is better than # define, especially when there is a pointer. See the example below:
Typedef char * pstr1;
# Define pstr2 char *;
Pstr1 S1, S2;
Pstr2 S3, S4;
In the preceding variable definition, S1, S2, and S3 are both defined as char *, while S4 is defined as char, which is not the expected pointer variable, the root cause is that # define is a simple string replacement, while typedef is a new name for a type.
# Define usage example:
# Define f (x) x * x
Main ()
Int A = 6, B = 2, C;
C = f (a)/F (B );
Printf ("% d \ n", C );
The output result of the following program is: 36.
For this reason, when # define definition is used in many C language programming specifications, if the definition contains expressions and must use parentheses, the above definition should be as follows:
# Define f (x) (x * X)
Of course, if you use typedef, there is no such problem.
4. Another example of typedef & # define
In the following code, the compiler reports an error. Do you know which statement is wrong?
Typedef char * pstr;
Char string [4] = "ABC ";
Const char * P1 = string;
Const pstr P2 = string;
Answer and analysis:
P2 error. Another reminder is that typedef is different from # define, which is not a simple text replacement. In the above Code, const pstr P2 is not equal to const char * P2. There is no difference between const pstr P2 and const long x in nature. They both impose read-only restrictions on variables, except that the data type of the variable P2 is defined by ourselves rather than the inherent type of the system. Therefore, the meaning of const pstr P2 is: P2 is a read-only variable whose data type is char *, so P2 is incorrect.
# Define and typedef Extension
1) # define macro definition has a special advantage: You can use # ifdef, # ifndef, and so on for logical judgment. You can also use # UNDEF to cancel definition.
2) typedef also has a special advantage: It complies with range rules, the type of a variable defined by typedef is restricted to the defined function or file (depending on the location of the variable definition), while the macro definition does not.
5. typedef & Complex Variable Declaration
In programming practices, especially when looking at other people's code, we often encounter complicated variable declarations and use typedef to simplify our own values, such:
The following is the declaration of three variables. I want to use typdef to define an alias for them. What should I do?
> 1: int * (* A [5]) (INT, char *);
> 2: void (* B [10]) (void (*)());
> 3. Doube (*) (* pA) [9];
Answer and analysis:
The method to create a type alias for a complex variable is very simple. You only need to replace the variable name with the type name in the traditional variable declaration expression, and then add the keyword typedef to the beginning of the statement.
> 1: int * (* A [5]) (INT, char *);
// Pfun is a type alias we created
Typedef int * (* pfun) (INT, char *);
// Declare an object using the new defined type, equivalent to int * (* A [5]) (INT, char *);
Pfun A [5];
> 2: void (* B [10]) (void (*)());
// First declare a new type for the blue part of the above expression
Typedef void (* pfunparam )();
// Declare a new type as a whole
Typedef void (* pfun) (pfunparam );
// Declare the object using the new defined type, which is equivalent to void (* B [10]) (void (*)());
Pfun B [10];
> 3. Doube (*) (* pA) [9];
// First declare a new type for the blue part of the above expression
Typedef double (* pfun )();
// Declare a new type as a whole
Typedef pfun (* pfunparam) [9];
// Declare an object using the new defined type, equivalent to Doube (*) (* pA) [9];
Pfunparam Pa;

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: 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.