First, I will reorganize the local variables a and 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; }
Now this is interesting, Timed_Val2 based on Timed_Val1 , they are both unsigned , so Timed_Val2 always >= Timed_Val1 . At first I could not understand that a might be true, but, as Mark Wilkins points out, he can if he turns around.
There is also only one case where they are equal, that is, when Timed_Val2==0 I am going to extract this as a special case to help readability. Then I can decompose the two > / < if into 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) {
So, I would say that this returns true iff (if and only if) sys_msec before Timed_Val1 or after Timed_Val1 + Timed_Val2 * 0.2 seconds .
As a final step, I would now rename the variables and comment on this.
//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); } } }
This does not mean that there is no better way to do this, but at least now it can be read.
source share