c++if-statementoperator-precedence

"IF" argument evaluation order?


if(a && b)
{
  do something;
}

is there any possibility to evaluate arguments from right to left(b -> a)?

if "yes", what influences the evaluation order?

(i'm using VS2008)


Solution

  • The evaluation order is specified by the standard and is left-to-right. The left-most expression will always be evaluated first with the && clause.

    If you want b to be evaluated first:

    if(b && a)
    {
      //do something
    }
    

    If both arguments are methods and you want both of them to be evaluated regardless of their result:

    bool rb = b();
    bool ra = a();
    
    if ( ra && rb )
    {
      //do something
    }