Matching a 2 by 2 condition in an if expression in C-family

When programming, I usually deal with two sets of conditions combined together, for example:

if (A && B){...}
else if (!A && B){...}
else if (A && !B){...}
else if (!A && !B){...}

It can also be resolved using nested if statements.

if (A){
    if (B) {...}
    else {...}
}
else {
    if (B) {...}
    else {...}
}

EDIT: Some new thoughts about which I first evaluate both A and B and save them as a temporary variable (then do as the first approach) if evaluating A and B does not have a side effect?


So my question is, is there a difference in performance between the two and how is their readability?

I am C ++ code, if any.

+4
source share
3 answers

. A B . A B , .

, , A B .

+5

, ( ). . , , ( , ) .

,

// Assuming A and B are either 0 or 1 
switch ((A * 2) + B) {
  case 0: ...; break;
  case 1: ...; break;
  case 2: ...; break;
  case 3: ...; break;
}

, .

+2

; , , -. , , ( - ).

, , :

int  Nested(int a)
{       
    if(a > 0)
    {
        if( a > 1)
        {
            if( a % 2 == 0)
            {
                if( a % 10 == 4)
                {
                    printf("a is valid");
                    return 1;
                }
                else
                {               
                    printf("a last digit inst 4");
                }
            }
            else
            {
                printf(" a is not odd");
            }    
        }
        else
        {
            printf(" a is not bigger than 1");
        }
    }
    else
    {
        printf(" a is not bigger than 0");
    }

    return 0;

}

int NotNested(int a)
{
    if(a <= 0)
    {
        printf(" a is not bigger than 0");
        return 0;
    }

    if(a <= 1)
    {
        printf(" a is not bigger than 1");
        return 0;
    }

    if(a % 2 != 0)
    {
        printf(" a is not odd");
        return 0;
    }

    if( a % 10 != 4)
    {
        printf("a last digit inst 4");
        return 0;
    }

    printf("a is valid");

    return 1;

}

, NotNested , .

, , .

0

Source: https://habr.com/ru/post/1649981/


All Articles