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

前端 未结 5 456
夕颜
夕颜 2020-12-13 12:14

I was just shocked, that this is allowed:

if( int* x = new int( 20 ) )
{
    std::cout << *x << \"!\\n\";
    // delete x;
}
else
{
    std::cout         


        
5条回答
  •  星月不相逢
    2020-12-13 12:19

    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.

提交回复
热议问题