Why are declarations in C and C ++ so complex?

Beginners are often surprised to learn that the declaration

int* a, b;

      

declares a

as a pointer to int

and b

how int

. This is due to the curious way of dividing declarations in C and C ++ into specifiers and declarators. A declaration starts with a single list of specifiers, but each declared object has its own declarator, which independently modifies the specifier to give the resulting object type. Thus, the above expression has two declarations, *a

and b

. *

in the first declaration is combined with a specifier int

to give the type int*

for a

, and the second declarator has no modifiers, so the resulting type is simple int

.

At the same time, in certain contexts, a type name (type-identifier in C ++) is expected, which is a combination of specifiers and possibly an "abstract declarator", which is basically a declarator that omits the name. int*

For example, this is the name of the type. But the type name is not used directly in declarations. As we can see above, it is int* a, b

not interpreted as a type name followed by two identifiers, as one would expect.

Thus, we have specifiers, declarators, and combinations of two formation type names, but type names are not used to declare variables of the respective types, even if they are literally type names that are only defined for the absence of a name.What are the historical reasons for such a grammar, complex and contradictory? Is there any benefit to being able to write code like this?

int *a, (*b)();

      

+3


source to share





All Articles