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
304 views
in Technique[技术] by (71.8m points)

c++ - Is a statement void(); legal and what is it actually?

I have a little piece of code which has a statement void();

int main() 
{
   void( ); // 1: parses fine in GCC 5.4.0 -Wpedantic 
   // void;    // 2: error declaration does not declare anything
} 

What is 1 void() exactly?

  • An anonymous function declaration?
  • A type declaration?
  • An empty expression?

What makes 1 void() different from 2 void;?

I have read already:

  1. Is sizeof(void()) a legal expression? but there void() is considered a type in sizeof
  2. What does the void() in decltype(void()) mean exactly? where it is considered in declspec.
  3. And I read Is void{} legal or not?

But I am curious if the loose statement void(); is different from one of those (and why of course)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

void; is an error because there is no rule in the language grammar which matches that code. In particular, there is no rule type-id ;,

However, the code void() matches two grammar rules:

  1. type-id .
  2. postfix-expression, with the sub-case being simple-type-specifier ( expression-list-opt ).

Now, the parser needs to match void(); to a grammar rule. Even though void() matches type-id, as mentioned earlier there is no rule that would match type-id ;. So the parser rejects the possible parsing of void() as type-id in this context, and tries the other possibility.

There is a series of rules defining that postfix-expression ; makes a statement. So void() is unambiguously parsed as postfix-expression in this context.

As described by the other answers you linked already, the semantic meaning of this code as a postfix-expression is a prvalue of type void.

Related link: Is sizeof(int()) a legal expression?


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

1.4m articles

1.4m replys

5 comments

57.0k users

...