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.
Direct Initialization or Assignment Operator (Syntax) This assigns the value of one object to another object both of which are already exists. Copy initialization is used when a new object is created with some existing object. This is used when we want to assign existing object to new object.
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
You explicitly initialize a class object when you create that object. There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
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-seqoptdecl-specifier-seq declarator=
initializer-clause
attribute-specifier-seqoptdecl-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".
Because the C++03 standard only allows assignment initialisation inside conditions:
condition:
expression
type-specifier-seq declarator = assignment-expression
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