从同一个bool c ++中获得两个if语句的最佳实践

Dan*_*JAB 1 c++ if-statement

我有一个if语句,[显然]只在条件为真时运行.在这个if语句之后,有一些应该总是运行的代码,之后是另一个应该在与第一个条件相同的条件下运行的if语句.

中间的代码使用堆栈的特定元素执行操作,任一侧的ifs分别在操作之前和之后执行堆栈上的push/pop.

所以逻辑是这样的:

  1. 我需要推送堆栈吗?是/否
  2. 在堆栈顶部执行操作
  3. 堆栈被推了吗?(如果是,那么弹出)

第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
//:::::::::::::::::::::::::::::::::::::::
Run Code Online (Sandbox Code Playgroud)

写完这篇文章后,我认为这样做可能更有效:

//:::::::::::::::::::::::::::::::::::::::
//  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
//:::::::::::::::::::::::::::::::::::::::
Run Code Online (Sandbox Code Playgroud)

我更喜欢第一种可读性方法,因为它被分成几行,而第二种方法在同一行中有两个赋值(=)和两个比较(==).我想知道是否更好地使用第二种方法(出于效率或可执行大小的原因)或者是否有比两者更好的方法.

在任何人说它只能产生几乎无法估量的差异之前,这是一个巨大的循环,必须在1/50秒内运行数千次,所以我希望尽可能多地节省时间.

Vla*_*lad 5

性能不应该是您关注的问题:现代编译器通常足够聪明,可以在任何情况下优化代码.如果代码基本上做同样的事情,结果将是相同的.

因此,您应该更喜欢更易读的变体(因此更易于维护).

我会写这样的东西:

ret = somefunction();
// I don't know what is the semantics of ret == 1, so let's imagine some
bool operationIsPush = (ret == 1);
bool operationIsOnTop = (ret == 2);

if (operationIsPush || operationIsOnTop)
{
    //conditional code
}

if (operationIsPush)
{
    //more conditional code
}

//unconditional code

if (operationIsPush || operationIsOnTop)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • +1,在分析器说出来之前,这不是问题. (2认同)