我有一個if語句[顯然]只有在條件爲真時才運行。在這個if語句之後,有一些代碼應該總是運行,之後是另一個if語句,它應該在與第一個語句相同的條件下運行。有兩個如果語句來自同一個布爾C++的最佳做法
中間的代碼使用堆棧中的特定元素執行操作,兩邊的if分別在操作前後執行堆棧上的push/pop操作。
這樣的邏輯是這樣的:
- 我需要推棧?是/否
- 在堆棧頂部執行操作
- 堆棧被推送了嗎? (如果是,則彈出)
項目1和3的條件相同。
這是我第一次寫這樣做在C++
#include <stdio.h>
#include <stdlib.h>
int somefunction(){
return rand() % 3 + 1; //return a random number from 1 to 3
}
int ret = 0;
//:::::::::::::::::::::::::::::::::::::::
// Option 1 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run = (ret = somefunction()) == 1; //if the return of the function is 1
run = (run || (ret == 2)); //or the return of the function is 2
if (run){ //execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 1 End
//:::::::::::::::::::::::::::::::::::::::
寫這個我想,這可能是更有效地做到這一點後,代碼:
//:::::::::::::::::::::::::::::::::::::::
// Option 2 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run;
if (run=(((ret = somefunction()) == 1)||ret == 2)){ //if the return of the function is 1 or 2 then execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 2 End
//:::::::::::::::::::::::::::::::::::::::
我更喜歡第一方法的可讀性,因爲它分成幾行,而第二行在同一行中有兩個賦值(=)和兩個比較(==)。 我想知道是否更好地使用第二種方法(出於效率或可執行文件大小的原因),或者如果有比這兩種方法更好的方法。
之前有人說它只會產生幾乎不可估量的差異,這是一個巨大的循環,必須在1/50秒內運行數千次,所以我想盡可能節省時間。
+1,直到剖析器這樣說,這不是問題。 – zoul 2012-07-19 11:12:22
我明白你的意思,但不一定是「如果IsPush」第一,然後「如果IsPush || IsOnTop」,然後另一個「如果IsPush」? 謝謝。 – DanJAB 2012-07-19 11:27:00
@DanJAB:你是對的,我已經調整了代碼 – Vlad 2012-07-19 11:50:11