我有一个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