在处理现有的大型源代码库时,我发现了这种构造的几个实例:
do
{
if (!a)
break;
something();
} while(false);
在什么情况下,这比(在我看来)更简单的更好
if (a)
{
something();
}
这种构造有很多实例,所以我认为它是有意的。不幸的是,编写该代码的人不在。
为什么第一种编写代码块的方式比第二种更可取?
这是一种实现GOTO
而不显式使用它的方法。
一般来说,我相信C放入if
语句,这样您就可以在结构化编程范式中进行编程。
维基百科的那篇文章指出,与范式的偏离将是提前退出,这将是do while (false)
的一个用例。然而,建议的用于处理早期退出的伪代码在while
循环中仍然不总是具有-false
条件。
对于处理有错误的文件的例子,它指出有人可能会这样写:
// open file
while (/* reading not finished */)
{
// read some data;
if (/* error */)
{
// stop the subprogram and inform rest of the program about the error;
// use of break here would skip the "process read data" step
}
// process read data;
}
// finish the subprogram;
此策略的一个不错的类比是从函数返回;如果这个代码在一个函数中,那么"break"将是一个"return false";然而,这在这里是不可能的,因为不能简单地突破C/C++中的任意代码范围。
随着越来越多的健全性检查和故障条件的建立,执行"中断"技巧可以防止嵌套变得毫无意义。是的,做事总是有更多的方法,但这种策略通常反映了功能的正常思维过程和工作流程,人们通常非常熟悉这种工作流程。
甚至可能是这样的情况:一个函数被移到另一个代码区域(可能是因为它太专业化了,永远不会被重用),重构"返回"驱动的逻辑是不值得的。
例如,这可能是一个更有意义的战略示范。我包含了一个不那么琐碎的设置来演示为什么你会看到这个:
intenseStructure = allocate_memory_and_other_expensive_things();
do {
if( ! some_test_of( variable1 ) ) {
some_log( "Unexpected value for variable1." );
break;
}
variable2 = some_thing_involving( variable1 );
if( ! some_test_of( variable2 ) ) {
some_log( "Unexpected value for variable2." );
break;
}
something();
} while(false);
delete intenseStructure;
在这里,我们假设在设置了"intensiteStructure"之前,我们无法对"variable1"进行有意义的测试,而"variable2"(需要"variable 1")也是如此。"做…同时(假)"策略反映了一种基于功能的方法:
bool do_something( Intense* intenseStructure ) {
if( ! some_test_of( variable1 ) ) {
some_log( "Unexpected value for variable1." );
return false;
}
variable2 = some_thing_involving( variable1 );
if( ! some_test_of( variable2 ) ) {
some_log( "Unexpected value for variable2." );
return false;
}
something();
return true;
}
intenseStructure = allocate_memory_and_other_expensive_things();
do_something( intenseStructure );
delete intenseStructure;
下面是一个更"传统"的if导向方式的例子。正如你所看到的,虽然行为相当,但它有点令人困惑。if语句的嵌套可能会在一段时间后变得非常麻烦和混乱,代码维护可能会变得非常困难:
intenseStructure = allocate_memory_and_other_expensive_things();
if( ! some_test_of( variable1 ) ) {
some_log( "Unexpected value for variable1." );
} else {
variable2 = some_thing_involving( variable1 );
if( ! some_test_of( variable2 ) ) {
some_log( "Unexpected value for variable2." );
} else {
something();
}
}
delete intenseStructure;
如果存在多个中断条件&如果不能使用switch,那么程序员通常使用do while
do
{
if (some cond)
{
// do some job
break;
}
else if (some cond)
{
// do some thing break
}
// similarly
}
while(false);
目标是在执行do表达式