在开始和结束条件下切换for循环

Switch the for loop basis on start and end condition

本文关键字:for 循环 条件下 开始 结束      更新时间:2023-10-16

我有一个下面的代码,其中我从传递给getUser方法的timestamp获得start值。并且我从current timestamp中得到了以毫秒为单位的end值。

start的最小值可以是0,而end的最大值可以是13。因此,如果start总是小于end,我下面的for循环将正常工作。

bool getUser(uint64_t timestamp) {
    uint64_t start = (timestamp / (60 * 60 * 1000 * 24))  % 14;
    struct timeval tp;
    gettimeofday(&tp, NULL);
    uint64_t ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
    uint64_t end = (ms / (60 * 60 * 1000 * 24))  % 14;
    for (uint64_t i = start; i<=end; i++) {

    }
}

但在某个时刻,start也可能大于end。也就是说,假设start的值是9end的值是2,那么我上面的for循环就不起作用了,因为在这种情况下,我想从9 to 2迭代我的for循环,它将是i = 9, 10, 11, 12, 13, 0, 1, 2

如何确保start小于endstart大于end,则我的上述for循环在这两种情况下都能正常工作。。

如果开始小于结束,我上面的for循环可以很好地工作,但它不适用于大于endstart

非常简单,因此可以理解。当然还有很大的改进空间。

if(start > end)
    end += 14;
for (uint64_t i = start; i<=end; i++) {
   // operate on i%14
}

为什么不使用while循环:

do{
    //code here
    ++start;
    if(start==14)
        start=0;
} while(start!=end);