我的c代码中有if
条件。如果if
条件为真,我需要调用sleep(1)
系统调用并再次检查if
条件。这必须最多进行9次。如果在9次中的任何时间,if
条件失败,我应该从函数返回。如果9次到期,我应该调用另一个函数。为了更清楚,我将在下面编写伪代码。
function1()
{
count = 0
label : if (condition)
{
count++
sleep(1);
if(count < = 9)
goto label;
}
if(count > 9)
{
return;
}
function2(); /* if(condition) failed */
return;
} /* End of function1() */
实现上述逻辑的最佳方法是什么。我不想使用goto
语句。
答案 0 :(得分:4)
你已经实现了for循环。这将是完全等效的,除非即使第一个condition
失败,计数也将为1:
function1()
{
for (count = 1; condition && count <= 9; count ++)
{
sleep(1);
}
if(count > 9)
{
return;
}
function2(); /* if(condition) failed */
return;
} /* End of function1() */
在C中,你通常从零开始计算,但这只是风格问题。
function1()
{
for (count = 0; condition && count < 9; count ++)
{
sleep(1);
}
if(count >= 9)
{
return;
}
function2(); /* if(condition) failed */
return;
} /* End of function1() */
编辑
最好使用单一的回报,而不是多次回复
function1()
{
for (count = 0; condition && count < 9; count ++)
{
sleep(1);
}
if(count < 9)
{
function2(); /* if(condition) succeeded within 9 tries */
}
} /* End of function1() */
答案 1 :(得分:1)
您可以将此重新排序为
for(count = 1; count <= 9; ++count)
{
if(!condition)
{
function2();
break;
}
sleep(1);
}
答案 2 :(得分:0)
为了使西蒙的答案满足我的需要,我正在修改他的答案。请告诉我是否有任何错误
function1()
{
for(count = 1; count <= 9; ++count)
{
if(!condition)
{
function2();
break;
}
sleep(1);
}
return;
} /* End of function1 */