Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const typedef; in C and C++

What was the original reason behind allowing statements like the following in C and C++?

const typedef;

It doesn't seem to make any practical sense.

Also, you can do this: const; and typedef;

Edit: @AndreyT points out it is not a standard defined behavior. For the full answer, I would like to know about any possible advantages that arose in front of GCC devs when they decided this type of code should be compilable.

like image 227
sasha.sochka Avatar asked Jul 13 '13 21:07

sasha.sochka


1 Answers

This looks like a degenerate form of declaration.

In C declaration is not a statement. It is a declaration. And what you have above is not allowed.

6.7 Declarations

2 A declaration shall declare at least a declarator (other than the parameters of a function or the members of a structure or union), a tag, or the members of an enumeration.

In C++ declaration is a statement. But still what you have above is not allowed. From C++03

7 Declarations

3 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.

If some compiler allows this in C or C++ code, it must be a quirk of that compiler. You should direct that question to its authors.

As you probably know, the syntax of C and C++ is not specified by the grammar alone. Doing it by the grammar alone would be too complicated or downright impossible. Some additional restrictions are imposed by the text that accompanies the grammar. Compilers usually treat the grammar itself with respect, but when it comes to those elaborate additional restrictions... many compilers allows some violations to slip through.

I would make an educated guess that this must be a side-effect of the "empty declaration" extension. Since the beginning of times empty declarations were illegal in C and C++. For example, this code has always been illegal

void foo() {}; // In file scope

because it follows function definition with an empty declaration. However, virtually all compilers accepted it, allowing empty declarations as an extension. For the very same reason you could write

;;;; // In file scope

in the middle of the file and have your code compile. What you have in your example is also an empty declaration, into which you added some inconsequential qualifiers and storage-class specifiers.

P.S. Correct me if I'm wrong, but C++11 legalized empty declarations. I'm not sure about C11.

like image 190
AnT Avatar answered Sep 25 '22 14:09

AnT