Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Understanding confusing typedef grammar

Consider the following code-snippet

typedef int type;
int main()
{
   type *type; // why is it allowed?
   type *k ;// which type?
}

I get an error 'k' is not declared in this scope. The compiler parses type *k as multiplication between type* and k. Isn't this grammar very confusing?

Why is type *type allowed by the C++ Standard? Because the grammar says so? Why?

question from:https://stackoverflow.com/questions/8489215/understanding-confusing-typedef-grammar

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

1 Reply

0 votes
by (71.8m points)
type *type; // why is it allowed?

C++11 3.3.2/1 says:

The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any)

So the variable name type is not introduced until after the use of the type name type; the type name is the only available meaning of type during the declarator.

type *k ;// which type?

The local variable name hides the global type name, so that is chosen here. This is described in C++11 3.3.10/1:

A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class.

The fully qualified type name, ::type, is of course still available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...