My understanding, for a long time now, was that a C++ translation unit, after the preprocessor has run, is a sequence of declarations (let me remind that any definition is also a declaration).
Many people have argued with this statement but no one has ever given a counterexample. But I myself found this example which troubles me:
int x; //declaration
; // ??? EMPTY DECLARATION?
int main() //dec
{ //la
} //ration
This compiles fine with MSVC and online comeau. I know the standard defines an empty statement but I never heard of an empty declaration. So, I see three options:
Please help me dissolve my doubts. Thanks
In C and C++ programming language terminology, a translation unit (or more casually a compilation unit) is the ultimate input to a C or C++ compiler from which an object file is generated.
In the field of translation, a translation unit is a segment of a text which the translator treats as a single cognitive unit for the purposes of establishing an equivalence. It may be a single word, a phrase, one or more sentences, or even a larger unit.
A translation unit is the basic unit of compilation in C++. This unit is made up of the contents of a single source file after it passes through preprocessing. It contains included any header files without blocks that are ignored using conditional preprocessing statements like ifdef, ifndef, etc.
Your understanding is correct and the standard (or at least Stroustrup) does define an empty declaration.
EDIT: It seems this answer is wrong (there's a semantic rule on the standard - but not on the book, as far as I can tell - that prohibits both decl-specified-seq
and init-declarator-list
of being empty at the same time). See Charles Bailey's answer.
n "The C++ Programming Language", appendix A, section A.4:
A program is a collection of
translation-unit
s (...). Atranslation-unit
, often called a source file, is a sequence ofdeclaration
s:
translation-unit:
declaration-seq_opt
opt
means the production is optional. In this rule, it means an empty translation unit is valid.
Section A.7:
declaration-seq:
declaration
declaration-seq declaration
declaration:
block-declaration
(...)
block-declaration:
simple-declaration
(...)
simple-declaration:
decl-specified-seq_opt init-declarator-list_opt ;
So declaration-seq
is a sequence of at least one declaration
. A declaration
can, amongst other things, be a block-declaration
, which in turn produces simple-declaration
. As both the decl-specified-seq
and init-declarator-list
non-literals are optional, ;
is a valid declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With