Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a variable in the condition part of an if-statement?

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.

like image 400
Kiril Kirov Avatar asked Sep 29 '12 18:09

Kiril Kirov


People also ask

Can I define a variable inside an if statement?

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.

Can you define variable in IF statement Python?

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.

Can we initialize a variable in if condition?

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".

How do you use if statement variables?

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.


2 Answers

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 } 
like image 193
pb2q Avatar answered Sep 19 '22 13:09

pb2q


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.

like image 25
Matthieu M. Avatar answered Sep 19 '22 13:09

Matthieu M.