在函数之间 toggle/flip/alternate 的优雅方式 (C)

Elegant way to toggle/flip/alternate between to functions (C)

有没有更优雅的方法来做这样的事情:

if(millis() - time >= 100) {
   time = millis();
   if(toggle == 1){
      dothis();
      toggle = 0;
   }
   else {
      dothat();
      toggle = 1;
   }
}

你可以这样做:

// if the condition is OK, then continue
if(!(millis() - time >= 100))
    return; // exit from the function

// common to both if and else cases
time = millis();

// toggles and does the first case if it was false,
// otherwise another case when it was true
(toggle ^= 1) ? dothat() : dothis();

切换toggle的另一种方法:

toggle = !toggle;

假设toggle为1,则!toggle为0,反之亦然

接近品味。恕我直言,切换的常用方法是 toggle = 1 - toggle;.

如果性能很重要,取消引用通常比测试更有效,因此您可以构建一个(指向)函数的数组:

typedef void (*dofunc)(void);
dofunc func[] = {&dothat, &dothis};
...
int toggle = 0;
...
if((t = millis()) - time >= 100) {
    time = t;
    func[toggle]();
    toggle = 1 - toggle;
}