typedef struct and struct

Source: Internet
Author: User
Tags anonymous constant data structures

Chapter One: the difference between typedef struct and struct

1. Basic explanations

A typedef is a C-language keyword that defines a new name for a data type. The data types here include the internal data type (INT,CHAR, etc.) and the custom data type (struct, etc.).

The purpose of using TypeDef in programming is generally two, one is to give the variable a new name that is easy to remember and meaning, and the other is to simplify some more complex type declarations.

As to what is so subtle about typedef, you should continue to look at the specific aspects of the problem.

2. typedef & Structure Issues

When defining a structure with the following code, the compiler reported an error. is the C language not allowed to include pointers to its own in the structure? Please guess first, then read the following explanation:

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

Answers and Analysis:

1, the most simple use of typedef

typedef long BYTE_4;

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

2, typedef and structure in combination with the use

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

This statement actually accomplishes two things:

1) Define a new type of structure

struct TAGMYSTRUCT
{
int iNum;
Long llength;
};

Analysis: Tagmystruct called "tag", or "tag", is actually a temporary name, the struct keyword and tagmystruct together, constitute this structure type, regardless of whether there is a TypeDef, this structure exists.

We can use struct tagmystruct varname to define variables, but it is important to note that it is wrong to use tagmystruct varname to define variables, because structs and tagmystruct together can represent a struct type.

2) typedef has a name for this 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 is of course allowed to include pointers to its own structure, and we can see countless examples of the implementation of data structures such as linked lists, and the fundamental problem with this code is the application of typedef.

According to our above description can know: The process of building a new structure encountered 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 established, the type of the new name also does not exist, That means the compiler doesn't know Pnode at all.

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 is not yet fully declared. The C language compiler supports this practice.

3), Standard practice:

typedef uint32 (* adm_readdata_pfunc) (uint16*, UInt32);

This has not been seen before, the personal think is Yu define a uint32 pointer function, uint16*, uint32 as a function of two parameters; should be equivalent to # define UINT32 (* adm_readdata_pfunc) (uint16*, UInt32);

Structs are common in two forms of code:
struct A
{
//...
};

struct
{
//...
A
This is actually two completely different uses:
The former is called "struct type definition", meaning: the structure in the definition {} is a struct with a name of "a".
This usage is typically in a typedef:
typedef struct TAGA//deliberately give a different name, as the real names of the struct body
{
//...
A The alias of the struct.

The latter is a struct variable definition, meaning: A variable named "a" is defined with the structure in {}. The struct here is called an anonymous struct and cannot be directly referenced.
You can also create an alias for an anonymous struct through a typedef so that it can be referenced:
typedef struct
{
//...
A Defines an anonymous struct with an alias of a

Chapter Two: differences between struct and typedef structs in C and C + +

There are three ways to define structures in C and C + +.

typedef struct {

int data;

int text;

} S1;

This method can define a S1 structure in C or C + +

struct S2 {

int data;

int text;

};

This definition can only be used in C + +, and if used in C, then the compiler will error

struct {

int data;

int text;

} S3;

This method does not define a structure, but rather defines a s3 structure variable, and the compiler will be S3 memory.

void Main ()

{

S1 mine1;//OK, S1 is a type

S2 mine2;//ok,s2 is a type

S3 mine3;//Ok,s3 is not a type

S1.data = 5;//ERRORS1 is a type

S2.data = 5;//ERRORS2 is a type

S3.data = 5;//OKS3 is a variable

}

In addition, there are several ways to define the variable that defines the structure itself in the structure.

struct S6 {

s6* ptr;

};

This notation can only be used in C + +

typedef struct {

s7* ptr;

} S7;

This is a definition that is wrong in C and C + +

If in C, we can use such a "curve to salvation" method

typedef struct tags8{

TagS8 * PTR;

} S8;

Article III: struct and typedef structs

Divided into three pieces to tell:
1 First:
To define a struct type in C, use a typedef:
typedef struct STUDENT
{
int A;
}stu;
So when declaring variables, you can: Stu stu1;
If there is no typedef, a struct Student stu1 must be used to declare
The Stu here is actually the alias of the struct student.
In addition here can also not write Student (so also can't struct Student stu1;)
typedef struct
{
int A;
}stu;
But in C + + It's simple, directly
struct Student
{
int A;
};
Therefore, the structure type student is defined, and the variables are declared directly student stu2.
===========================================
2 Second:
If you use typedef in C + +, it will make a difference:
struct Student
{
int A;
}STU1;//STU1 is a variable
typedef struct STUDENT2
{
int A;
}STU2;//STU2 is a struct type
Direct access to stu1.a when used
But the STU2 must first STU2 S2;
Then s2.a=10;
===========================================
3 Master the above two, but in the end we'll talk about a problem that doesn't matter much.
If in the C program we write:
typedef struct
{
int num;
int age;
}AAA,BBB,CCC;
What the hell is this?
I personally observe the understanding of the compiler (VC6), which is equivalent to
typedef struct
{
int num;
int age;
}AAA;
typedef AAA BBB;
typedef AAA CCC;
That is to say, AAA,BBB,CCC are all structural types. Any one can be used to declare a variable, as is the case in C + +. But what you should note is that in C + + if the typedef keyword is written out, then AAA,BBB,CCC will be a distinct three object.

Fourth: The use of typedef structs and structs in C + +

struct _X1 {...} X1; and typedef struct _x2{...} x2; What's the difference.

In fact, the former is an object instance x1 that defines classes _x1 and _x1, which is the class name _x2 that defines classes _x2 and x2,

So they are used in the process of taking something else. See Example 1.

[Knowledge Point]

Structs are also a type of data that can be used with structural variables, so, like other types of variables, they are defined first when using structural variables.

The general format for defining structure variables is:

struct structure name

{

Type variable name;

Type variable name;

...

} structure variables;

The struct name is a struct identifier and is not a variable name.

Another common format is:

typedef struct struct Name

{

Type variable name;

Type variable name;

...

} structure alias;

Also note: In C, a struct cannot contain a function. In C + +, structs are extended and can contain functions.

======================================================================

Example 1:struct.cpp

#include <iostream>

using namespace Std;

typedef struct _point{

int x;

int y;

}point; Define class, give class an alias

struct _hello{

int x, y;

} Hello; Define classes and objects at the same time

int main ()

{

Point pt1;

pt1.x = 2;

PT1.Y = 5;

cout<< "ptpt1.x=" << pt1.x << "pt.y=" <<pt1.y <<endl;

Hello pt2;

pt2.x = 8;

PT2.Y = 10;

cout<< "pt2pt2.x=" << pt2.x << "pt2.y=" <<pt2.y <<endl;

The above hello Pt2; this line of compilation will not pass. Why?

Because Hello is an object instance that has been defined.

The correct practice is as follows: with Hello.x and HELLO.Y

hello.x = 8;

HELLO.Y = 10;

cout<< "hellohello.x=" << hello.x << "hello.y=" <
return 0;

}

Fifth: Quiz

Q: What is the difference between defining a struct with a struct and a typedef struct? Why there are two ways of it.

struct Student
{
int A;
} Stu;
typedef struct STUDENT2
{
int A;
}STU2;

A:

In fact, this thing is inherited from the C language, typedef can define a new compound type or an alias for an existing type, in C, if you use
struct XXX
{
}; method, you must use struct XXX var to declare the variable, and use the
typedef struct
{
} method can be written as xxx var;
However, there is no such thing in C + +, no matter which one you use, you can declare the variable in the second way, this should be the dregs of C language.

Summary of Usage

first to fourth use

Use one:

Defines an alias for a type, not just a simple macro substitution. Can be used as multiple objects that declare a pointer type at the same time. Like what:
char* PA, PB; The majority does not conform to our intent, it only declares a pointer to a character variable,
and a character variable;
The following are possible:
typedef char* PCHAR; General capitalization
PCHAR PA, PB; It is possible to declare two pointers to a character variable
Although:
Char *pa, *PB;
Also feasible, but relatively not in the form of TypeDef intuitive, especially in the need of a large number of pointers, the way typedef is more convenient.

use two:

Used in the old C code (specific How old is not checked), to help the struct. In the previous code, when declaring a struct new object, you had to bring a struct with the form: struct struct name Object name, such as:
struct TAGPOINT1
{
int x;
int y;
};
struct tagPOINT1 p1;

In C + +, you can write directly: the name of the struct name object, which is:
TagPOINT1 P1;

It is too much trouble to think that someone often writes a struct, so they invent:
typedef struct TAGPOINT
{
int x;
int y;
}point;

Point P1; This is less than the original way to write a struct, more convenient, especially in the large use of time

Perhaps, in C + +, this use of TypeDef is not very large, but understanding of it, to master the old code is still helpful, after all, we may encounter in the project earlier legacy code.

use three:

Use typedef to define platform-independent types.
For example, to define a floating-point type called REAL, on the target platform one, let it represent the highest precision type:
typedef long double REAL;
On platform two that does not support long double, replace the following:
typedef double REAL;
On three platforms that are not supported by double, replace the following:
typedef float REAL;
That is, when cross-platform, just change the typedef itself, do not make any changes to other source code.
This technique is widely used by the standard library, such as size_t.
In addition, because typedef defines a new alias for a type, it is not a simple string substitution, so it is more robust than a macro (although using macros can sometimes accomplish the above purposes).

use four:

Define a new, simple alias for a complex claim. The method is: in the original declaration gradually replaced with the alias part of a complex declaration, so loop, the part with the variable name to the last substitution, get the original declaration of the most simplified version. Example:

1. Original declaration: Int * (*A[5]) (int, char*);
The variable name is a, and replacing a with a new alias Pfun is possible:
typedef int * (*PFUN) (int, char*);
The most streamlined version of the original statement:
Pfun A[5];

2. Original declaration: void (*b[10]) (void (*) ());
The variable name is B, replace the right part in parentheses, and Pfunparam as alias one:
typedef void (*pfunparam) ();
Replace the left variable B,pfunx with the alias two:
typedef void (*PFUNX) (Pfunparam);
The most streamlined version of the original statement:
Pfunx B[10];

3. Original declaration: Doube (*) () (*e) [9];
Variable named E, replace the left part first, Pfuny as alias one:
typedef double (*pfuny) ();
Replace the right variable E,pfunparamy with the alias two
typedef PFUNY (*pfunparamy) [9];
The most streamlined version of the original statement:
Pfunparamy e;

Understand the right-left rule that is available for complex declarations:
From the variable name, first to the right, then to the left, encountered a round bracket to reverse the direction of reading, after the analysis in parentheses out of parentheses, or the first right after the left order, so loop, until the entire declaration analysis is complete. Example:
Int (*func) (int *p);
First find the variable name func, there is a pair of parentheses outside, and the left is a * number, which means that func is a pointer, then jump out of this parenthesis, first look to the right, and also encounter parentheses, which means (*func) is a function, so func is a pointer to such a function, that is, a function pointer, Such functions have a formal parameter of type int*, and the return value type is int.
Int (*func[5]) (int *);
The right side of the Func is a [] operator, stating that Func is an array with 5 elements, and the left side of the Func has a *, stating that the element of Func is a pointer (note that this is not the modifier func, but the func[5], because [] operator precedence is higher than *, and Func is preceded by [] Combined). Jumping out of this parenthesis, looking to the right, and encountering parentheses, the element of the Func array is a pointer to the function type, which points to a function that has a int* type parameter and a return value of type int.

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

second, two big traps

Trap One:

Remember, TypeDef is a new alias that defines a type, unlike macro, which is not a simple string substitution. Like what:
Define first:
typedef char* PSTR;
And then:
int mystrcmp (const PSTR, const PSTR);

The const PSTR is actually equivalent to a const char*. No, it's actually equivalent to char* Const.
The reason is that const gives the entire pointer itself to be constant, that is, to form a constant pointer char* const.
Simply put, remember that when the const and typedef appear together, the typedef will not be a simple string substitution.

Trap Two:

A typedef is syntactically a keyword that stores a class (such as auto, extern, mutable, static, register, and so on), although it does not really affect the storage characteristics of an object, such as:
typedef static INT INT2; Not feasible
The compilation will fail with the hint "more than one storage class has been specified".

The above information is from: http://blog.sina.com.cn/s/blog_4826f7970100074k.html Author: Red Dragon

Third, typedef and #define的区别

Case one:

In general, typedef are better than # define, especially where pointers are available. Take a look at the example:

typedef char *PSTR1;

#define PSTR2 char *;

PSTR1 S1, S2;

PSTR2 S3, S4;

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.