首先我重构出a
局部b
变量。
int TestTimeOut(unsigned long Timed_Val1, unsigned long Timed_Val2)
{
Timed_Val2 = Timed_Val1 + (Timed_Val2 * 200);
const int a = (Timed_Val1 > Timed_Val2) && (sys_msec < Timed_Val1) && (sys_msec > Timed_Val2);
const int b = (Timed_Val1 < Timed_Val2) && ((sys_msec < Timed_Val1) || (sys_msec > Timed_Val2));
return a || b;
}
现在这很有趣,是Timed_Val2
基于Timed_Val1
,他们都是unsigned
如此。起初我看不出不可能是真的,但正如马克威尔金斯指出的那样,如果它环绕,它可以。Timed_Val2
>= Timed_Val1
a
然而,也只有一种情况它们是相等的,那就是当Timed_Val2==0
我将把它作为一种特殊情况提取出来以提高可读性。然后我可以将两个>
/<
语句分解为if
.
int TestTimeOut(unsigned long Timed_Val1, unsigned long Timed_Val2)
{
if (Timed_Val2==0) return FALSE;
{
Timed_Val2 = Timed_Val1 + (Timed_Val2 * 200);
if (Timed_Val1 > Timed_Val2)
{ //this happens when it wraps around past 2^32
return (sys_msec < Timed_Val1) && (sys_msec > Timed_Val2);
}
else
{
return (sys_msec < Timed_Val1) || (sys_msec > Timed_Val2);
}
}
}
所以我会说这返回真当且仅当当且仅当sys_msec
是 beforeTimed_Val1
或 after Timed_Val1 + Timed_Val2 * 0.2 seconds
。
作为最后阶段,现在我将重命名变量并对其进行注释。
//Returns true iff time is before startTime_msec or after timeoutPeriods of 0.2 seconds
//startTime_msec - millisecond value compariable to sys_msec
//timeoutPeriods - the number of timeout periods of 0.2 seconds each
int TestTimeOut(const unsigned long startTime_msec, const unsigned long timeoutPeriods)
{
if (timeoutPeriods==0) return FALSE;
{
const unsigned long maxTime_msec = startTime_msec + (timeoutPeriods * 200);
if (startTime_msec > maxTime_msec)
{ //this happens when it wraps around past 2^32
return (sys_msec < startTime_msec) && (sys_msec > maxTime_msec);
}
else
{
return (sys_msec < startTime_msec) || (sys_msec > maxTime_msec);
}
}
}
这并不是说没有更好的方法可以做到这一点,但至少现在它是可读的。