Cpp - Defining Variables in if Statements

Introduction

You can define and initialize a variable within an if statement.

The expression is true if converting the variable's value to a bool type yields true.

The variable is available within the if statement.

if( int x = func() ) 
{ 
   . . . // Here to work with x. 
}           

The return value of the function, func(), is used to initialize the variable x.

If this value is not 0, the statements in the next block are executed.

The variable x no longer exists after leaving the if statement.

Related Topic