2017-03-27 33 views
0

因此,在查看大量interweb後,我無法找到答案。如果在if條件中聲明,如何將C三態語句轉換爲if/else?

說我有這段代碼:

if(P4IN & GPIO_PIN1?0:1){ 
     if (state==1){ 
      state = 0; 
      //Wait for this state to pass -- ends up saving the current state on button press. 
      while (counter < 10000){ 
       counter++; 
      } 
     } 
     else{ 
      state = 1; 
      while (counter < 10000){ 
       counter++; 
      } 
     } 
    } 

我將如何改寫這個讓if(P4IN & GPIO_PIN1?0:1)不會這樣寫的。我不介意創建額外的if/else條件或擴展此代碼塊(用於MSP432)

感謝您的時間。

+7

'如果(P4IN&GPIO_PIN1?0:1)' - >'如果(!(P4IN&GPIO_PIN1))' –

+1

...你如果輸入引腳連接到外部開關,應該(可能)管理去抖動 – LPs

+2

請注意'&'具有比三元更高的優先級,所以原來的語句本可以使用一些元素來更清晰。 – stark

回答

7

可以簡化整個事情到這一點:

if (!(P4IN & GPIO_PIN1)) { 
    state = !state; 

    while (counter < 10000) { 
    counter++; 
    } 
} 
+2

...或'state^= 1;'....;) – LPs