auto in if clause - the way to define parameters inside if

65 views Asked by At

I want to define a parameter inside if . for example

if(MyDataPtr && auto* InfoPtr = MyDataPtr ->extractInfo())

And gen compilation error Expected ')' Is it impossible? or what ca be done? - i don`t like the code bellow - looking for better (elegant) implementation

if(MyDataPtr)
{
   auto* InfoPtr = MyDataPtr ->extractInfo();
   if (InfoPtr )
     //some code
}
2

There are 2 answers

0
Some programmer dude On

Unfortunately you can't define variables in the middle of expressions. But you can define a variable as a single expression and use it as a condition, which will simplify your code a little bit:

if (MyDataPtr)
{
    if (auto InfoPtr = MyDataPtr->extractInfo())
    {
        // Use InfoPtr...
    }
}

Is it more "elegant"? To some perhaps.

0
Aykhan Hagverdili On

After C++ 17, you can do this:

if (T* InfoPtr; MyDataPtr && (InfoPtr = MyDataPtr->extractInfo()) {
    // use InfoPtr
}