Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c++ - Please explain syntax rules and scope for "typedef"

What are the rules? OTOH the simple case seems to imply the new type is the last thing on a line. Like here Uchar is the new type:

typedef unsigned char Uchar;

But a function pointer is completely different. Here the new type is pFunc:

typedef int (*pFunc)(int);

I can't think of any other examples offhand but I have come across some very confusing usages.

So are there rules or are people just supposed to know from experience that this is how it is done because they have seen it done this way before?

ALSO: What is the scope of a typedef?

question from:https://stackoverflow.com/questions/2427739/please-explain-syntax-rules-and-scope-for-typedef

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Basically a typedef has exactly the same syntax as an object declaration except that it is prefixed with typedef. Doing that changes the meaning of the declaration so that the new identifier declares an alias for the type that the object that would have been declared, had it been a normal declaration, would have had.

A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.

e.g.

Declares an int:

int a;

Declares a type that is an alias for int:

typedef int a_type;

Declares a pointer to a char:

char *p;

Declares an alias for a char *:

typedef char *pChar;

Declares a function pointer:

int (*pFn)(int);

Declares an alias for the type that is 'pointer to a function taking int and returning int':

typedef int (*pFunc)(int);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...