Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is condition evaluation optimized ? Is this code bad?

1.Imagine condition if (obj.is_x() || obj.is_y() || obj.is_z())
Will obj.is_y() and obj.is_z() be called and evaluated if obj.is_x() returned true ?

2.Is this a bad idea(in general)? Does this code look bad ?

bool isbn13_prefix_valid (const string& prefix)
{
    unsigned num = stoi(prefix);
    if (num == 978 || num == 979) return 1;  //super common ones
        else if (   num >= 0 && num <= 5 || num == 7 || num >= 600 && num <= 649
                || num >= 80 && num <= 94 || num >= 950 && num <= 989
                || num >= 9900 && num <= 9989 || num >= 99900 && num <= 99999)
            return 1;
    return 0;
}
like image 470
user3565923 Avatar asked Dec 04 '25 14:12

user3565923


1 Answers

  1. No, it will not, due to short-circuiting.

  2. Yes, that code looks bad. Not because it's incorrect, but because you're stuffing an extremely long conditional into a single if statement. Try refactoring your code to make it cleaner.

like image 76
Sam Estep Avatar answered Dec 07 '25 02:12

Sam Estep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!