Huang-zh
Huang-zh

Reputation: 147

A branch of an if-statement cannot be just a declaration?

A branch of an if-statement cannot be just a declaration. If we need to introduce a name in a branch, it must be enclosed in a block.------by TC++PL 4th.

void f1(int i)
{
    if (i)
        int x = i + 2;        //error: declaration of if-statement branch
}

But it makes sense on compilers of VS2013 and GCC4.8.

And Working draft(N3242) shows me that

If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement.

the code can be equivalently rewritten as:

void f1(int i)
{
    if (i) {
        int x = i + 2;
    }
}

Thus after the if statement, x is no longer in scope.

So what is the standard?

Upvotes: 2

Views: 760

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263467

Syntactically, a declaration can be a statement. Specifically, it's a declaration-statement.

(I say "can be" because not all declarations are statements. For example, a declaration at file scope, where a statement cannot legally appear, is not a statement.)

Since the syntax of an if statement is:

if ( condition ) statement

or

if ( condition ) statement else statement

it's perfectly legal for either branch of an if statement to be a declaration.

In your example, it's not particularly useful, but I can easily imagine that you might want to declare an object for the purpose of executing its constructor and/or destructor.

A branch of an if-statement cannot be just a declaration. If we need to introduce a name in a branch, it must be enclosed in a block.------by TC++PL 4th.

I have a PDF copy of "The C++ Programming Language", 4th edition, 4th printing, dated April 2015. The statement in 9.3 that "A declaration is a statement." is still there. That statement is incorrect, or at least incomplete. The statement that:

A branch of an if-statement cannot be just a declaration. If we need to introduce a name in a branch, it must be enclosed in a block.

is no longer there; it's been updated to:

The scope of a declaration of a branch of an if-statement is just that branch. If we need to introduce a name in a branch, it must be enclosed in a block (§9.2).

That's not strictly correct, but it's true that if you want a declaration in a branch, you need to enclose it in a block if you want to refer to it in a statement. A branch consisting of just a declaration is legal but usually not useful.

(Incidentally, C has different rules. C has permitted mixed declarations and statements since the 1999 standard, but it doesn't treat declarations as statements, so in C a declaration can't be a branch of an if statement.)

Upvotes: 6

Related Questions