Pro/con: Initializing a variable in a conditional statement

前端 未结 12 1221
Happy的楠姐
Happy的楠姐 2021-01-01 18:24

In C++ you can initialize a variable in an if statement, like so:

if (CThing* pThing = GetThing())
{
}

Why would one consider this bad or g

12条回答
  •  离开以前
    2021-01-01 19:03

    About the advantages:

    It's always recommended to define variables when you first need them, not a line before. This is for improved readability of your code, since one can tell what CThing is without scrolling and searching where it was defined.

    Also reducing scope to a loop/if block, causes the variable to be unreferenced after the execution of the code block, which makes it a candidate for Garbage Collection (if the language supports this feature).

提交回复
热议问题