Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it allowed to have a declaration without a name? [duplicate]

While reading the standard, I was really surprised to see that actually, the name is optional in a declaration:

struct Magic {};
int main() {
  int; // well-formed
  Magic; // well-formed
}

For those interested to read the standard, it's because in a simple-declaration, the init-declarator-list is optional. Here's a demo.

And so I really want to know why this is allowed. Why would I ever want to do that? It really makes no sense to me. My reasoning is that, because if it makes no sense, why allow it?

like image 398
Rakete1111 Avatar asked Jan 10 '18 17:01

Rakete1111


1 Answers

According to the C++ Standard (7 Declarations)

5 In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (Clause 9) or enumeration (7.2), that is, when the decl-specifier-seq contains either a class-specifier, an elaborated-type-specifier with a class-key (9.1), or an enum-specifier....

Thus this code

int main() {
  int; // well-formed
  Magic; // well-formed
}

is ill-formed.

Moreover formally these ill-formed declarations are definitions according to the paragraph #2 of the section 3.1 Declarations and definitions and obviously as such do not make sense.

like image 172
Vlad from Moscow Avatar answered Oct 15 '22 10:10

Vlad from Moscow