Ela*_*nda 56 c c++ syntax if-statement logical-operators
我读了一些遗留代码:
if ( 1 || !Foo() )
Run Code Online (Sandbox Code Playgroud)
是否有任何理由不写:
if ( !Foo() )
Run Code Online (Sandbox Code Playgroud)
Luc*_*ore 134
两者不一样.第一个永远不会评估,Foo()因为1短路||.
为什么要这样做 - 可能有人想强制进入then分支进行调试,并将其留在那里.它也可以说,这是源代码控制之前写的,所以他们不想要的代码丢失,而只是绕过了现在.
Mar*_*oun 44
if (1 || !Foo() )永远满意.!Foo()由于短路评估,甚至无法达到.
当您想要确保if执行下面的代码时,会发生这种情况,但您不想删除其中的实际条件,可能是出于调试目的.
可能对您有所帮助的其他信息:
if(a && b)- 如果a是false,b将不会被检查.if(a && b)- 如果a是true,b将被检查,因为如果是false,表达式将是false.if(a || b)- 如果a是true,b将不会被检查,因为true无论如何.if(a || b)- 如果a是false,b将被检查,因为如果b是,true那么它将是true.强烈建议有一个用于此目的的宏,这样DEBUG_ON 1可以更容易理解程序员的意思,而不是在代码中有魔术数字(谢谢@grigeshchauhan).
Lih*_*ihO 11
1 || condition
Run Code Online (Sandbox Code Playgroud)
无论是否真实,condition都是真的.在这种情况下,condition甚至从未评估过.以下代码:
int c = 5;
if (1 || c++){}
printf("%d", c);
Run Code Online (Sandbox Code Playgroud)
输出5因为c永远不会增加,但是如果你改变1了0,c++那么实际上会被调用,从而产生输出6.
通常的实际用法是,当您想要测试某些代码时,只有在满足评估为true的条件时才会调用这些代码:
if (1 || condition ) {
// code I want to test
}
Run Code Online (Sandbox Code Playgroud)
这种方式condition永远不会被评估,因此// code I want to test总是被调用.但它绝对不一样:
if (condition) { ...
Run Code Online (Sandbox Code Playgroud)
这是一个condition实际将被评估的声明(在你的情况下Foo将被调用)
Pat*_*ckV 10
问题得到了正确回答 - 区别在于操作的右侧是短路的,这表明这是强制进入if块的调试代码.
但是为了最佳实践的利益,至少我粗略地尝试了最佳实践,我建议替代方案,以增加偏好(最好的是最后):
注意:在我编写示例之后注意到这是一个C++问题,例子是C#.希望你能翻译.如果有人需要我,只需发表评论.
在线评论:
if (1 /*condition*/) //temporary debug
Run Code Online (Sandbox Code Playgroud)
外线评论:
//if(condition)
if(true) //temporary debug
Run Code Online (Sandbox Code Playgroud)
名称指示功能
//in some general-use container
bool ForceConditionForDebug(bool forcedResult, string IgnoredResult)
{
#if DEBUG
Debug.WriteLine(
string.Format(
"Conditional {0} forced to {1} for debug purposes",
IgnoredResult,
forcedResult));
return forcedResult;
#else
#if ALLOW_DEBUG_CODE_IN_RELEASE
return forcedResult;
#else
throw new ApplicationException("Debug code detected in release mode");
#endif
#endif
}
//Where used
if(ForceConditionForDebug(true, "condition"))...
//Our case
if(ForceConditionForDebug(true, "!Foo()"))...
Run Code Online (Sandbox Code Playgroud)
如果您想要一个非常强大的解决方案,您可以向源代码控制添加一个存储库规则,以拒绝任何调用ForceConditionForDebug的已检入代码.这段代码永远不应该以这种方式编写,因为它显然不会传达意图.它永远不应该被签入(或者已被允许签入)(源代码控制?同行评审?)并且绝对不应该允许它以当前形式在生产中执行.
| 归档时间: |
|
| 查看次数: |
3708 次 |
| 最近记录: |