A summary of the use of typedef

Source: Internet
Author: User
Tags define definition int size
A summary of the use of typedef

 

These two days, while looking at the program, it is found that there are many places where a typedef is used, defined in a structure, and some arrays are used in large quantities. But some places are not very clear, this afternoon, I would like to study. The Internet search, a lot of information. Sum up:

SOURCE One: Using typedef to curb miscreant Code

A Typedef declaration helps to create platform-independent types and even hides complex and incomprehensible syntax. In any case, using a typedef can bring unexpected benefits to your code, and you can learn to use typedef to avoid imperfections, making your code more robust.
A typedef declaration, called a TypeDef, creates a new name for an existing type. For example, people often use a typedef to write more beautiful and readable code. The so-called aesthetics, meaning that the typedef can hide clumsy syntax constructs and platform-related data types, thereby enhancing portability and future maintainability. This article will make every effort to uncover the powerful features of the typedef and how to avoid some common pitfalls.
How do I create a platform-independent data type that hides awkward and incomprehensible syntax?

Use typedefs to create synonyms for an existing type.

Define type names that are easy to remember
The most common use of a typedef is to create a type name that is easy to remember, and use it to archive the programmer's intent. The type is now declared in the variable name, located on the right side of the ' typedef ' keyword. For example:

typedef int size;

This declaration defines a synonym for int, with a name of size. Note that a typedef does not create a new type. It simply adds a synonym to an existing type. You can use size in any context that requires int:

void measure (Size * psz); 
Size array[4];
Size len = File.getlength ();

A typedef can also mask conforming types, such as pointers and arrays. For example, you don't have to repeatedly define an array of 81 character elements as follows:

Char line[81];
Char text[81];

Defines a typedef that you can do whenever you want to use an array of the same type and size:

typedef char LINE[81]; 
line text, secondline;
Getline (text);

Similarly, you can 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 parameters for the ' const char * ' type. Therefore, it may mislead people to declare mystrcmp () as follows:

This is wrong, in order, ' const PSTR ' is interpreted as ' char * const ' (a constant pointer to char), not ' const char * ' (a pointer to a constant char). This problem is easy to solve:

typedef const CHAR * CPSTR; 
int mystrcmp (CPSTR, CPSTR); It's right now.

Remember: whenever you declare a typedef for a pointer, add a const to the final typedef name so that the pointer itself is a constant, not an object.

Code simplification
The typedef behavior discussed above is somewhat like #define macro, replacing synonyms with its actual type. The difference is that the TypeDef is interpreted at compile time, so the compiler is allowed to deal with text substitutions beyond preprocessor capabilities. For example:

typedef int (*PF) (const char *, const char *);

This declaration introduces the PF type as synonymous with the function pointer, which has two parameters of the const char * type and a return value of type int. This typedef is essential if you want to use the following form of a function declaration:

PF Register (pf pf);

The parameter of the Register () 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. Let me show you how to implement this declaration without a typedef:

int (*register int (*PF) (const char *, const char *)) 

Few programmers understand what it means, let alone the risk of error caused by this convoluted code. Obviously, using typedef here is not a privilege, but a necessity. Skeptics may ask, "OK, does anyone still write this code?" "A quick glance at the header file <csinal> that reveals the signal () function, a function with the same interface.

typedef and Storage class keywords (storage class specifier)
This is not a bit surprising, the TypeDef, like Auto,extern,mutable,static, is a storage-class keyword, as is the register. This is to say that a typedef really affects the storage characteristics of an object; it simply says that the TypeDef declaration looks like a variable declaration of a type such as Static,extern on the composition of the statement. Here's a second trap:

typedef register INT Fast_counter; Error

compilation does not pass. The problem is that you can't have multiple storage-class keywords in the declaration. Because the symbol typedef already occupies the location of the storage class keyword, the register (or any other storage class keyword) cannot be used in a typedef declaration.

Promotion of Cross-platform development
There is another important use of TypeDef, which is to define machine-independent types, for example, you can define a floating-point type called real, and on the target machine it can achieve the highest precision:

On a machine that does not support long double, the typedef looks like the following:

And, on a machine that does not have a double, the typedef looks like this:

You can compile the real-type application on each platform without making any changes to the source code. The only thing to change is the typedef itself. In most cases, even this tiny change can be done automatically through wonderful conditional compilation. Isn't it? The standard library uses typedef extensively to create such platform-independent types: Size_t,ptrdiff and fpos_t are examples. In addition, a typedef like std::string and Std::ofstream also hides a long, incomprehensible template-specific syntax, such as: Basic_string<char, Char_traits<char> Allocator<char>> and Basic_ofstream<char, char_traits<char>>.

  author
Danny Kalev is a software engineer who specializes in C + + and formal language theory through a certified System analyst. He was a member of the C + + standards Committee from 1997 to 2000. He recently completed his master's thesis in the field of general linguistics with outstanding results. 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 went to some C + + forums and regularly wrote articles for different C + + websites and magazines. He also teaches programming languages and applied language courses at educational institutions.

SOURCE two: (http://www.ccfans.net/bbs/dispbbs.asp?boardid=30&id=4455)
The use of TypeDef in C language
1. Basic explanation

A typedef is a keyword in the C language that 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.).

There are two commonly used typedef in programming, one is to give variables a new name that is easy to remember and meaningful, and the other is to simplify some of the more complex type declarations.

As for the subtlety of the TypeDef, please take a look at the specific elaboration of several issues.
 2. typedef & Structure Issues

When you define a struct with the following code, the compiler reports an error. is the C language not allowed to include pointers to itself in the structure? Please guess first, then read the following note:

 

typedef struct TAGNODE
{
Char *pitem;
Pnode Pnext;
} *pnode;

  Answer and Analysis :

1, the most simple use of the typedef

 

typedef long BYTE_4;

Give a new name to a known data type long, called Byte_4.

  2. The combination of typedef and structure use

 

typedef struct TAGMYSTRUCT
{
int inum;
Long llength;
} mystruct;

This statement actually accomplishes two things:

1 Define a new structure type

 

struct TAGMYSTRUCT
{
int inum;
Long llength;
};

Analysis: Tagmystruct called "tag", that is, "tag", is actually a temporary name, struct keyword and tagmystruct together, constitute the structure of this type, whether there is a TypeDef, this structure exists.
We can use struct tagmystruct varname to define variables, but note that it is wrong to use tagmystruct varname to define variables, because struct and tagmystruct together can represent a struct type.
2 The typedef has a name for the new structure called MyStruct.

 

typedef struct TAGMYSTRUCT mystruct;

Therefore, MyStruct is actually equivalent to struct tagmystruct, and we can use MyStruct varname to define variables.
  Answers and analysis
C language, of course, allows the structure to contain a pointer to its own, we can build a list of data structures such as the implementation of the countless examples, the fundamental problem of the above code is the application of the typedef.
As we can see from the above description: The new structure was established in the process of encountering the Pnext domain declaration, the type is pnode, to know that Pnode represents the type of the new name, then the type itself has not been completed, the type of the new name also does not exist, In other words, the compiler does not know Pnode at this time.

There are several 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 a typedef to give a new name to a type that has not yet been fully declared. The C language compiler supports this practice.

3), Normative practice:

 

struct Tagnode
{
Char *pitem;
struct Tagnode *pnext;
};
typedef struct TAGNODE *pnode;

 3. typedef & #define的问题

There are two different ways to define PSTR data types. Which is a little better.

 

typedef char *PSTR;
#define PSTR char *;

  Answer and Analysis :
Generally speaking, a typedef is better than a #define, especially in a pointer situation. Take a look at the example:

 

typedef char *PSTR1;
#define PSTR2 char *;
PSTR1 S1, S2;
PSTR2 S3, S4;

In the above variable definition, s1, S2, S3 are all defined as char *, and S4 is defined as char, not the pointer variable we expect, and the root cause is that #define is just a simple string replacement and the typedef is a new name for a type.

#define用法例子:

 

#define F (x) x*x
Main ()
{
int a=6,b=2,c;
C=f (a)/F (b);
printf ("%d//n", c);
}

The output of the following program is: 36.
For this reason, in the case of many C programming specifications that refer to the use of the #define definition, if the definition contains an expression and must use parentheses, the definition above should be defined as follows:

 

#define F (x) (x*x)


Of course, if you use a TypeDef, there is no such problem.
  4. typedef & #define的另一例

The compiler in the following code will report an error, do you know which statement is wrong?

 

typedef char * PSTR;
Char string[4] = "ABC";
const char *P1 = string;
Const PSTR P2 = string;
p1++;
p2++;

  Answer and Analysis :
It was p2++ that made a mistake. This question once again reminds us that typedef and #define are different, and that it is not a simple text replacement. The const PSTR P2 in the above code is not equal to the const char * p2. The const PSTR P2 and const long x are essentially indistinguishable, with read-only restrictions on the variable, except that the data type of the variable P2 here is our own definition rather than the intrinsic type of the system. Therefore, the meaning of the const PSTR P2 is that a variable that qualifies the data type char * is P2 read-only, and therefore p2++ error.

#define与typedef引申谈
1) #define宏定义有一个特别的长处: You can use #ifdef, #ifndef等来进行逻辑判断, and you can use #undef to cancel the definition.
2 The typedef also has a special advantage: it conforms to the scope rule, and the variable type defined by the TypeDef is scoped to the defined function or file (depending on where the variable is defined), and the macro definition does not have this attribute.
  5. typedef & Complex Variable declarations
In programming practice, especially when looking at other people's code, we often encounter more complex variable declarations, and using typedef for simplification has its own value, such as:
Here are three variable declarations, I would like to use typdef to define an alias for them, how to do.

 

>1:int * (*a[5]) (int, char*);
>2:void (*b[10]) (void (*) ());
>3. Doube (*) () (*PA) [9];

  Answer and Analysis :

A simple way to create a type alias for a complex variable is simply 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 that we built
typedef int * (*PFUN) (int, char*);
Declares an object using a new type of definition, equivalent to int* (*a[5]) (int, char*);
Pfun a[5];

>2:void (*b[10]) (void (*) ());
Declare a new type
typedef void (*pfunparam) () first for the blue portion of the expression above;
Declares a new type as a whole
typedef void (*pfun) (Pfunparam);
Declares an object with the new type defined, equivalent to void (*b[10]) (void (*) ());
Pfun b[10];

>3. Doube (*) () (*PA) [9];
First declare a new type for the above expression Blue section
typedef double (*pfun) ();
Declare a new type as a whole
typedef pfun (*pfunparam) [9];
Declares an object with the new type defined, 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: 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.