Home > Net >  Decrementing inside of an if statement C
Decrementing inside of an if statement C

Time:10-24

I am confused as to how to have equivalent logic without having the the decrement inside of the if statement.

if(A && !B && !(C--))
{
} 

I thought that this is equivalent to:

if(A && !B && !(C))
{
    C--;
} 

CodePudding user response:

In the first example, C is decremented if the first two conditions are true.

In the second example, C is decremented if all three conditions are true.

The difference is that if !C is not true (the third condition is false), the first example will decrement C while the second will not.

CodePudding user response:

As a few before me have pointed out, the operator && uses short-circuit evaluation. That means !B will be evaluated only if A is fulfilled and !(C--) will be evaluated only if A && !B is fulfilled.

(Well, unless there are some user defined && operators in the mix but better to not think about that.)

The equivalent code would be:

if(A && !B && !(C))
{
    C--;
}
else if(A && !B)
{
    C--;
}

or

if(A && !B)
{
    if (!(C))
    {
        // Assuming you don't use "C" here.
    }
    C--;
}

CodePudding user response:

The postfix-decrement operator will decrement C when it executes, and return the old (pre-decrement) value. So your first code snippet is more equivalent to:

int postdecrement(int & c)
{
   int ret = c;
   c = c-1;
   return ret;
}

if(A && !B && !(postdecrement(C)))
{
    // empty
}

Note that your second code snippet was different from your first one in that your second snippet, C would only be decremented in the case where C was already 0.

  •  Tags:  
  • c
  • Related