Quentin
Quentin

Reputation: 63124

Direct-initializing an object inside a condition

It is possible to define and copy-initialize a variable inside the condition of an if statement :

if(int i = 17) { ... }

This also works with user-defined types, given that they overload operator bool :

if(Foo f = 42)      { ... }
if(Foo f = Foo(43)) { ... }

Why can't I use direct-initialization, like the following ?

if(Foo f(51)) { ... }

GCC emits error: expected primary-expression before 'f'.

Live on Coliru

Is there a reason other than "because the grammar says so" ? And how can I work around it ?

I'm working with VC++03, where Foo :

... so I'd rather avoid copying it or repeating its type.

Note : Although my actual problem is with C++03, I'm (academically) interested about answers in C++11.

Upvotes: 11

Views: 374

Answers (3)

Anton Savin
Anton Savin

Reputation: 41301

Given your restrictions, I believe in C++03 your only option is to declare the variable outside the if statement, adding braces for scoping:

{
    Foo f(51, 52);
    if (f) {
        //...
    }
}

In C++11 you could exploit braced initialization syntax:

if (Foo f{51, 52}) {
    //...
}

Upvotes: 2

Columbo
Columbo

Reputation: 60989

In C++03, one could solely use the copy-initialization syntax:

selection-statement:
       if ( condition ) statement
        […]

condition:
       expression
       type-specifier-seq declarator = assignment-expression

Since C++11, list-initialization was added:

condition:
        expression
       attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
       attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

The syntax of direct-initialization, i.e. Foo f(…), was presumably avoided for the same reason it was disallowed for non-static data member initializers: Ambiguities, in particular the "most vexing parse".

Upvotes: 11

Alexander Balabin
Alexander Balabin

Reputation: 2075

Because the C++03 standard only allows assignment initialisation inside conditions:

condition:
    expression
    type-specifier-seq declarator = assignment-expression

Upvotes: 2

Related Questions