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
148 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 Answer

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.


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

...