On 09/26/2013 03:10 AM, David Brown wrote:
....
with C99 you can declare (and initialise) your variables anywhere that
you can have a statement
Not exactly. It's only in the block-item-list of a compound statement
that declarations and statements are interchangeable. In all of the
other contexts where a statement is allowed, a declaration is not allowed:
label: statement
case 1: statement
default: statement
if(x) statement
else statement
switch (y) statement
while(z) statement
do statement while(a);
for(int i=0; i<n; i++) statement
Of course, a compound statement is itself a statement, and can therefore
be put in any of those locations, and can contain a declaration - but
you can't put in a bare declaration in any of those locations.
I confess to being surprised by the first three examples. If I hadn't
bothered checking, I would have expected to be able to put bare
declarations in those locations. Having to wrap such a declaration in a
compound statement would limit its scope to that compound statement.
However, an empty statement followed by a declaration is permitted, and
would have the same practical effect as allowing a declaration in those
locations, so it's not an onerous restriction, just a surprising one (at
least to me).
For each of the last six examples, the statement is also a block, which
means that if a declaration were allowed there, the scope of the
declaration would end at the terminating semi-colon. Such a declaration
would be completely useless (except for any side-effects of the
initializers) which is probably why declarations are not allowed in
those locations.
In C++, declarations are statements, and as such are allowed in all of
those locations. That makes more sense in C++ than it would in C,
because a simple declaration of an object that goes out of scope
immediately can still be a very active piece of code, because of the
automatically invoked constructor and destructor.