const typedef; in C and C++ - 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.

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.

Related

It seems the current standard draft cannot interpret why two structured binding declaration conflict with each other

struct A{
int a;
};
struct B{
int b;
};
auto&& [x] = A{}; //#1
auto&& [x] = B{}; //#2
int main(){
}
In this example, all compilers give an error that the x at #2 conflicts with that introduced at #1. However, IIUC, there's no rule in the post-C++20 working draft standard which can interpret what's the reason.
First, in my opinion, the declaration at #2 and the declaration at #1 declare the same entity. They correspond due to:
basic.scope#scope-3
Two declarations correspond if they (re)introduce the same name, both declare constructors, or both declare destructors, unless
[...]
They declare the same entity per basic.link#8
Two declarations of entities declare the same entity if, considering declarations of unnamed types to introduce their names for linkage purposes, if any ([dcl.typedef], [dcl.enum]), they correspond ([basic.scope.scope]), have the same target scope that is not a function or template parameter scope, and either
they appear in the same translation unit, or
[...]
So, as far as now, they declare the same entity and they shouldn't be considered as potentially conflict per basic.scope#scope-4
Two declarations potentially conflict if they correspond and cause their shared name to denote different entities([basic.link]). The program is ill-formed if, in any scope, a name is bound to two declarations that potentially conflict and one precedes the other ([basic.lookup]).
Since they denote the same entity, as aforementioned, they do not potentially conflict.
They still do not violate this rule:
basic.link#11
For any two declarations of an entity E:
If one declares E to be a variable or function, the other shall declare E as one of the same type.
[...]
Since structured bindings are not mentioned in this list, they do not violate this rule. Similar, they do not violate One-definition rule
No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, template, default argument for a parameter (for a function in a given scope), or default template argument.
At least, according to what the relevant rules say, the two declarations in this example shouldn't result in any program ill-formed. If I don't miss some other rules, Can it be considered as vague in the standard which cannot interpret why two structured binding declarations conflict with each other in this case? This case is more underspecified in the N4861
This is just a missing case in [basic.link]/11: that if one (of the two declarations) declares a structured binding, the program is ill-formed. (One could alternatively merely require that the other also declare a structured binding and then extend the list in [basic.def.odr]/1, but that’s more complicated and suggests that it might be possible to redefine it in another translation unit.)
You are citing text from a working draft of a post-C++20 version of the language. As such, the behavior it describes is not likely implemented by any compiler currently existing. As it is a working draft, it likely contains a number of language defects and/or bugs, so trying to learn from it is not a productive activity.
All of the "correspond" language you cite is adopted from P1787, which is not part of any C++ standard actual compilers implement. As such, compilers are providing you with the C++20 functionality, and under those rules, these clearly conflict.
There may be some defective wording in P1787, but that's expected with complex proposals and working drafts of a standard. File a defect report on it.

Legality of empty, unnamed enumeration specifier

In the example in §7.5 (C++14) one finds:
enum {}; // ill-formed
But, technically speaking, I think the code is valid.enum {} is an enum-specifier, and so, it's a type-specifier, which is a decl-specifier, and thus, it is a simple-declaration with an omitted init-declarator-list. And this is accepted by §7.5. Note that the identifier is optional for an unscoped enumeration. Also, clang compiles this with a warning.
Edit
In relation to the answers mentioning that the *decl-specifier-seq* shall introduce one or more names into the program, or shall redeclare a name introduced by a previous declaration, I show below a typedef declaration that compiles, but whose decl-specifier-seq doesn't introduce any name in the declaration:
typedef class {} A;
In the C++14 FD, right above your example, it is explained why the declaration is ill-formed:
In a simple-declaration, the optional init-declarator-list can be
omitted only when declaring a class (Clause 9) or enumeration (7.2)
[…]
In such cases, the decl-specifier-seq shall introduce one or more
names into the program, or shall redeclare a name introduced by a
previous declaration.
Hence
enum {} e;
enum {a};
Are valid - our quote does not apply to the first declaration as it includes an init-declarator, and the second one introduces the name a as an enumerator. Note that GCC won't compile the first declaration, which is presumably a bug.
You also mentioned the quote
If the enumerator-list is empty, the underlying type is as if the
enumeration had a single enumerator with value 0.
This makes a statement about the underlying type, not the enumeration itself, and is thus irrelevant for this matter.
Why does typedef class {} A; compile?
A is an init-declarator. Yes, it is - [dcl.dcl]/9:
If the decl-specifier-seq contains the typedef specifier, the
declaration is called a typedef declaration and the name of each
init-declarator is declared to be a typedef-name
I.e. the names declared as typedef-names are the init-declarators, by this definition. Hence there is an init-declarator-list, and our above quote isn't applicable.
If you look through the standard, you'll find quite a few things that would be accepted at a purely syntactical level, but are prohibited by the text. This is just one of many instances of that basic idea.
Many of these situations are pretty obvious. Let's consider a really trivial one: a floating point number. Using a syntactical notation similar to that of the standard we could get something like:
"-"opt digits opt "."opt digits opt ("e" "-"opt digits)opt
Everything there is "optional". That doesn't, however, mean that nothingness should be taken as a number. Nor does it mean that (for example) .e is a valid floating point number. It does mean that almost any individual piece can be omitted if some of the others are present. You don't need digits both before and after the decimal point, so each is optional in itself--but one or the other has to be present, so 1. and .1 are both valid, but just . isn't. Likewise, the . is optional as well--something like 1e50 is a perfectly valid floating point literal, even though it doesn't contain a . anywhere.
Those limitations are expressed in the text associated with the syntactic notation itself. What's allowed (or not) has to based on everything taken together, not just on one piece in isolation.
There is clear written in the Standard that (7 Declarations)
...In such cases, and except for the declaration of an unnamed bit-field (9.6), the decl-specifier-seq shall introduce one or more
names into the program, or shall redeclare a name introduced by a
previous declaration.
This declaration
enum {}; // ill-formed
does not satisfy the requirement. It introduces neither name into the program.
As for typedef(s) then
7.1.3 The typedef specifier 1 Declarations containing the decl-specifier typedef declare identifiers that can be used later
for naming 94)

Why are there a handful of passing mentions of "function prototypes" in C++11? Surely these don't exist in C++

The C++11 standard makes a couple of passing mentions to "function prototypes".
There are not in any definitions of the relevant features, but in random places like:
"function prototype scope" in [C++11: 3.3.4] (whose definition actually admits it's talking about "function declarations");
an editorial description of the library type definition clauses in [C++11: 17.5.1.4/1], footnote 175 (which seems to be referring to the C functionality);
[C++11: 20.9.4.3/6] which describes the hypothetical template <T> typename add_rvalue_reference<T>::type create(); as "a function prototype".
the same thing at [C++11: 20.9.6/4];
appendix [C++11: C.1.7] which talks about declarators in C: "The function declarations using C incomplete declaration style must be completed to become full prototype declarations, then later "Rationale: Prototypes are essential to type safety".
... and that's it.
Surely, we are set on the "declaration"/"definition" terminology and, since the C++ standard does not use the "prototype" terminology in its core definitions, these are merely typos/inconsistencies, introduced because some editors are familiar with C terminology?
Or is there some subtle meaning I'm missing?
Yes and no. I think some of the uses of "prototype" make sense, but others should really be changed to "declaration".
I agree that §3.3.4/1 should talk about "function declaration scope" instead of "function prototype scope".
§17.5.1.4 is talking about C++ headers, so I think it should probably use "declaration" instead of prototype.
Footnote 175 is specifically referring to what is provided by C headers, so there I think it's probably appropriate to use C terminology (i.e., to continue to use "prototype", though possibly with an added note that this is equivalent to a C++ declaration).
I'd agree that the use of "prototype" at §20.9.6/4 and §20.9.4.3/6 are both mistakes, and should use "declaration" instead.
C.1.7 is specifically comparing C to C++, talking about declarations vs. prototypes in C and how they compare to C++ declarations, so it nearly needs to retain the use of "prototype" to be meaningful.
As to a definition of "prototype" (or related features), ISO 9899:1999 (through TC 3) is a normative reference to the C++ standard, so its definition of "prototype" can be applied since the C++ standard itself provides none.

Why is the 'Declare before use' rule not required inside a class? [duplicate]

This question already has answers here:
Do class functions/variables have to be declared before being used?
(5 answers)
Closed 4 years ago.
I'm wondering why the declare-before-use rule of C++ doesn't hold inside a class.
Look at this example:
#ifdef BASE
struct Base {
#endif
struct B;
struct A {
B *b;
A(){ b->foo(); }
};
struct B {
void foo() {}
};
#ifdef BASE
};
#endif
int main( ) { return 0; }
If BASE is defined, the code is valid.
Within A's constructor I can use B::foo, which hasn't been declared yet.
Why does this work and, mostly, why only works inside a class?
Well, to be pedantic there's no "declare before use rule" in C++. There are rules of name lookup, which are pretty complicated, but which can be (and often are) roughly simplified into the generic "declare before use rule" with a number of exceptions. (In a way, the situation is similar to "operator precedence and associativity" rules. While the language specification has no such concepts, we often use them in practice, even though they are not entirely accurate.)
This is actually one of those exceptions. Member function definitions in C++ are specifically and intentionally excluded from that "declare before use rule" in a sense that name lookup from the bodies of these members is performed as if they are defined after the class definition.
The language specification states that in 3.4.1/8 (and footnote 30), although it uses a different wording. It says that during the name lookup from the member function definition, the entire class definition is inspected, not just the portion above the member function definition. Footnote 30 additionally states though that the lookup rules are the same for functions defined inside the class definition or outside the class definition (which is pretty much what I said above).
Your example is a bit non-trivial. It raises the immediate question about member function definitions in nested classes: should they be interpreted as if they are defined after the definition of the most enclosing class? The answer is yes. 3.4.1/8 covers this situation as well.
"Design & Evolution of C++" book describes the reasoning behind these decisions.
That's because member functions are compiled only after the whole class definition has been parsed by the compiler, even when the function definition is written inline, whereas regular functions are compiled immediatedly after being read. The C++ standard requires this behaviour.
I don't know the chapter and verse of the standard on this.
But if you would apply the "declare before use" rule strictly within a class, you would not be able to declare member variables at the bottom of the class declaration either. You would have to declare them first, in order to use them e.g. in a constructor initialization list.
I could imagine the "declare before use" rule has been relaxed a bit within the class declaration to allow for "cleaner" overall layout.
Just guesswork, as I said.
The most stubborn problems in the definition of C++ relate to name lookup: exactly which uses of a name refer to which declarations? Here, I'll describe just one kind of lookup problem: the ones that relate to order dependencies between class member declarations. [...]
Difficulties arise because of conflicts between goals:
We want to be able to do syntax analysis reading the source text once only.
Reordering the members of a class should not change the meaning of the class.
A member function body explicitly written inline should mean the same thing when written out of line.
Names from an outer scope should be usable from an inner scope (in the same way as they are in C).
The rules for name lookup should be independent of what a name refers to.
If all of these hold, the language will be reasonably fast to parse, and users won't have to worry about these rules because the compiler will catch the ambiguous and near ambiguous cases. The current rules come very close to this ideal.
[The Design And Evolution Of C++, section 6.3.1 called Lookup Issues on page 138]

Static Constant Class Members

Consider the following snippet:
struct Foo
{
static const T value = 123; //Where T is some POD-type
};
const T Foo::value; //Is this required?
In this case, does the standard require us to explicitly declare value in a translation unit? It seems I have conflicting information; boost and things like numeric_limits from the STL seem to do this sort of thing just like in my snippet.
OTOH, I remember reading somewhere (albeit a long long time ago) that you're still required to provide a declaration in a translation unit.
If this is the case, what about template specialization? Will each specialization require a declaration?
I'd appreciate your comments as to what the "right way" is.
You have to provide a definition in a translation unit too, in case you use the value variable. That means, if for example you read its value.
The important thing is that the compiler is not required to give a warning or error if you violate that rule. The Standard says "no diagnostic required" for a violation.
In the next C++ Standard version, the rule changed. A variable is not used when it is used as a constant expression. Simply reading value above where the variable is initialized directly in the class means that still no definition is required then.
See the definition of use in section 3.2 One Definition Rule of the Standard and requirement for a definition for static data-members in 9.4.2, paragraph 4 and 5 (in the C++98 Standard. Appears in paragraph 3 and 4 in the n2800 draft of the next Standard).
Correction: The rule already changed for c++03: If the variable appears where a integral constant expression is required, no definition is needed (quoting from an unofficial revisions list for the 2003 update), see resolution for this language defect report:
An expression is potentially evaluated unless it appears where an integral constant expression is required (see 5.19), is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8)...
Note that even then, many uses are in cases where an integral constant is not required. Cases where one is, is in array dimensions or in template metaprogramming. So strictly speaking (see this report), only the c++1x solution provides really guarantee that in obvious cases also like "s == string::npos" where an integral constant is not required the definition of the static member is not needed, because the next Standard has a different, better wording of 3.2. This is however quite theoretical stuff, since most (all?) compiler don't moan anyway. Thanks for the guy in the comment section for telling me.
To add on to what litb said, from my copy of n2798:
9.4.2
[...]
2 The declaration of a static data member in its class definition is not a definition and
may be of an incomplete type other than cv-qualified void. The definition for a static
data member shall appear in a namespace scope enclosing the member’s class definition. In
the definition at namespace scope, the name of the static data member shall be qualified
by its class name using the :: operator.
You don't have to provide a definition for static integral constant members if you don't use them in some way that requires them to be stored in memory somewhere (e.g. take the address of such a member). See Stroustrup's The C++ Programming Language, section 10.4.6.2.
Edit:
Oops, I just re-read the question, and the question was for some type T. In general you would need to provide a definition, I agree. But if you used something from the int family, you wouldn't necessarily have to (with the caveat above).