ste*_*enj 16 c++ if-statement coding-style
在C++中,您可以在if语句中初始化变量,如下所示:
if (CThing* pThing = GetThing())
{
}
Run Code Online (Sandbox Code Playgroud)
为什么会考虑这种糟糕或好的风格?有什么好处和坏处?
我个人喜欢这种风格,因为它限制了pThing变量的范围,因此当它为NULL时永远不会意外使用它.但是,我不喜欢你不能这样做:
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
Run Code Online (Sandbox Code Playgroud)
如果有办法完成上述工作,请发布.但如果那是不可能的,我仍然想知道为什么.
小智 19
重要的是C++中的声明不是表达式.
bool a = (CThing* pThing = GetThing()); // not legit!!
Run Code Online (Sandbox Code Playgroud)
您不能在if语句中同时执行声明和布尔逻辑,C++语言规范特别允许表达式或声明.
if(A *a = new A)
{
// this is legit and a is scoped here
}
Run Code Online (Sandbox Code Playgroud)
我们如何知道在一个表达式中是否在一个术语和另一个术语之间定义?
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
Run Code Online (Sandbox Code Playgroud)
咬紧牙关并使用内部if.范围规则很有用,您的逻辑是明确的:
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在里面有初始化语句if您可以在C++17内部和switch自。
您的代码现在是:
if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())
{
// use pThing here
}
// pThing is out of scope here
Run Code Online (Sandbox Code Playgroud)