Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve C++ style for simple conditions

I am new to programming. I am doing my homework and the codes work so I won't post my whole codes out. I just wonder if it is possible to add "&&" and "||" in the same condition - my condition is a must be equal to 16 and b equal to any number from 5-9. Any suggestions? e.g.

if ( a == 16)
    {
        if (b == 5 || b == 6 || b == 7 || b == 8 || b == 9 )
        {
        printf("you pass\n");
        }
    }

Thanks a lot :)

like image 527
jessycaaaa Avatar asked Mar 02 '23 08:03

jessycaaaa


1 Answers

Yes; just do it, and use parentheses to make it unambiguous:

if ((a == 16) && (b == 5 || b == 6 || b == 7 || b == 8 || b == 9))

or, if b is an integer:

if (a == 16 && b >= 5 && b <= 9)

Ideally, though, you would describe the meaning of these chains of conditions using names, then come up with a much more expressive bit of code:

const bool theFooIsOkay = (a == 16);
const bool theBarIsGood = (b >= 5 && b <= 9);

if (theFooIsOkay && theBarIsGood)
{
   // ...
}
like image 109
Asteroids With Wings Avatar answered Mar 12 '23 13:03

Asteroids With Wings