I was just shocked, that this is allowed:
if( int* x = new int( 20 ) ) { std::cout << *x << "!\n"; // delete x; } else { std::cout << *x << "!!!\n"; // delete x; } // std:cout << *x; // error - x is not defined in this scope
So, is this allowed by the standard or it's just a compiler extension?
P.S. As there were several comments about this - please ignore that this example is "bad" or dangerous. I know what. This is just the first thing, that came to my mind, as an example.
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
Yes. It is also true for for scope. But not functions of course. In your example: if the condition in the if statement is false, x will not be defined though.
C++17 If statement with initializer Now it is possible to provide initial condition within if statement itself. This new syntax is called "if statement with initializer".
If you define the variable inside an if statement, than it'll only be visible inside the scope of the if statement, which includes the statement itself plus child statements. You should define the variable outside the scope and then update its value inside the if statement.
This is allowed by the specification, since C++98.
From Section 6.4 "Selection statements":
A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition.
The following example is from the same section:
if (int x = f()) { int x; // ill-formed, redeclaration of x } else { int x; // ill-formed, redeclaration of x }
Not really an answer (but comments are not well suited to code samples), more a reason why it's incredibly handy:
if (int* x = f()) { std::cout << *x << "\n"; }
Whenever an API returns an "option" type (which also happens to have a boolean conversion available), this type of construct can be leveraged so that the variable is only accessible within a context where it is sensible to use its value. It's a really powerful idiom.
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