& | 與&& || 的區(qū)別

& 和 | 總是要計(jì)算兩個(gè)操作數(shù),將操作符兩邊的操作數(shù)按位與/或運(yùn)算。
&& 和 || 先檢查第一個(gè)操作數(shù)的值,再根據(jù)該值進(jìn)行操作,可能根本就不處理第二個(gè)操作數(shù),進(jìn)行的是布爾運(yùn)算。
在其他語(yǔ)言中也被叫做短路布爾表達(dá)式(Short-circult boolean expressions)。
x = (y != 0) && ( z / y > 5 );
如果y為0則會(huì)導(dǎo)致“除0錯(cuò)誤”,所以可以先判斷y的值,如果y為0則不會(huì)進(jìn)行除法運(yùn)算。

例:

/*
     * The condition for this PT_WAIT_UNTIL is a little tricky: the
     * protothread will wait here until all data has been acknowledged
     * (data_acked() returns true) and until all data has been sent
     * (send_data() returns true). The two functions data_acked() and
     * send_data() must be called in succession to ensure that all
     * data is sent. Therefore the & operator is used instead of the
     * && operator, which would cause only the data_acked() function
     * to be called when it returns false.
     */
    PT_WAIT_UNTIL(&s->psockpt, data_acked(s) & send_data(s));

static char data_acked(register struct psock *s)
{
  if(s->state == STATE_DATA_SENT && uip_acked()) {
    if(s->sendlen > uip_mss()) {
      s->sendlen -= uip_mss();
      s->sendptr += uip_mss();
    } else {
      s->sendptr += s->sendlen;
      s->sendlen = 0;
    }
    s->state = STATE_ACKED;
    return 1;
  }
  return 0;
}

static char send_data(register struct psock *s)
{
  if(s->state != STATE_DATA_SENT || uip_rexmit()) {
    if(s->sendlen > uip_mss()) {
      uip_send(s->sendptr, uip_mss());
    } else {
      uip_send(s->sendptr, s->sendlen);
    }
    s->state = STATE_DATA_SENT;
    return 1;
  }
  return 0;
}

uip中 psock_send() 函數(shù)為了實(shí)現(xiàn)連續(xù)發(fā)送,需要每次檢測(cè)上一次發(fā)送的是否收到了收到確認(rèn),并會(huì)發(fā)送數(shù)據(jù)(如果data_acked() 返回為false則為重發(fā),否則發(fā)送下一段數(shù)據(jù))。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容